Android - Spinner

Android Spinner is just like the combox box or drop down menu of AWT or Swing in java. It is used to display multiple options to the user in which only one item can be selected by him. Android spinner is associated with AdapterView to retrive the list of items. So you need to use one of the adapter classes with spinner.Adapter classes is responsible for Layout design and contents of spinner widget. Android Spinner class is the subclass of AsbSpinner class.

Create a New Android Project

Open Android Studio and create a new Project to test ImageView UI Widget.

You can view this blog to know
how to create a Project in Android

Make Design for XML Layout

Open activity_main.xml from android resources and remove everything.Drag an Relative Layout and then drag a Spinner on Layout in Graphical mode of IDE.
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="dzone.jaipur.myapp1.MainActivity" >

  <Spinner  
        android:id="@+id/spinner1"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:layout_alignParentTop="true"  
        android:layout_centerHorizontal="true"  
        android:layout_marginTop="83dp" />

</RelativeLayout>

Code in you Activity Class

Your java File (Android Activity) should look like this..


public class MainActivity extends AppCompatActivity {

  String[] country = { "India", "USA", "China", "Japan", "Other",  };



	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

    Spinner spin = (Spinner) findViewById(R.id.spinner1);
        spin.setOnItemSelectedListener(MainActivity.this);

        //Creating the ArrayAdapter instance having the country list
        ArrayAdapter aa = new ArrayAdapter(this,android.R.layout.simple_spinner_item,country);
        aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //Setting the ArrayAdapter data on the Spinner
        spin.setAdapter(aa);

    }
    public void onItemSelected(AdapterView arg0, View arg1, int position,long id) {
        Toast.makeText(getApplicationContext(),country[position] ,Toast.LENGTH_LONG).show();
    }

    @Override
    public void onNothingSelected(AdapterView arg0) {
        // TODO Auto-generated method stub

    }

	

}


Program output on emulator screen

Now Run the Application on your virtual device and get the desired output.


       

Why Us?

Address

  • 257,katewa nagar,gujjar ki thadi,new sanganer road, Jaipur, Jaipur
  • Phone:+919829708506
  • Email:[email protected]

Follow Us