Learn Android Development For Beginners

Spinner

The Spinner control is used to select one value from the list of values. It is like a dropdown control available in other programming languages. The spinner control uses adapter to bind list of values.

Spinner

For understanding create new project and add Spinner control in the main activity file

 <spinner android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/spinner"
            android:spinnermode="dropdown"
            android:popupbackground="#a1a1a1" />

Spinner control has some important properties that needs to be understand.

  • android:spinnerMode: it can have two values ‘dropdown’ or ‘dialog’. The default value of the spinnermode is the dialog which shows list in dialog. The dropdown mode shows the values in dropdown list.

  • android:prompt: The prompt sets the title on the top of the list.

  • popupBackground: it sets the background color of the popup dialog of spinner.

Create ArrayAdapter in the code file and pass context, layout item id and list of countries in constructor. Find the Spinner control in layout and call the setAdapter method to set adapter.

 private void BindList() {

    ArrayList<string> listToBind = GetCountriesList();
    ArrayAdapter arrayAdapter = new ArrayAdapter(getApplicationContext(), 
                                android.R.layout.simple_spinner_item, listToBind);
        
    Spinner spinner = (Spinner)findViewById(R.id.spinner);
    spinner.setAdapter(arrayAdapter);

 }

 private ArrayList<string> GetCountriesList()
 {

    String[] array = {"Armenia", "Austria","Azerbaijan", "Belgium", "Denmark","France",
                      "Georgia", "Germany","Greece", "Hungary", "Ireland","Italy",
                      "Monaco", "Portugal", "Spain", "Sweden","Switzerland",
                      "Turkey","Ukraine","United Kingdom"};
 
   return  new ArrayList<string>(Arrays.asList(array));

 }

android.R.layout.simple_spinner_item is built-in resource for spinner item. Pass it as parameter to ArrayAdapter constructor.

Pass Custom Layout id for Spinner item:

Android also provides a way to add extra styling on the spinner item. Create new xml file in layout folder and name it “my_spinner_item.xml” and add the TextView control in it.

 <?xml version="1.0" encoding="utf-8" ?>
 <textview xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@android:id/text1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textsize="20sp"
        android:textcolor="#ff0000" />

In the layout file add new Spinner control.

 <spinner android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/spinner2"
            android:prompt="@string/custom_spinner"
            android:spinnermode="dialog" />

In code file create instance of ArrayAdapter and pass R.layout.my_spinner_item as item’s layout resource and set adapter of the spinner control.

private void BindList2() {

    ArrayList<string> listToBind = GetCountriesList();
    ArrayAdapter arrayAdapter = new ArrayAdapter(getApplicationContext(), 
                                      R.layout.my_spinner_item, listToBind);

    arrayAdapter.setDropDownViewResource( R.layout.my_spinner_item);

    Spinner spinner = (Spinner)findViewById(R.id.spinner2);
    spinner.setAdapter(arrayAdapter);

}

For setting the layout resource for dialog call setDropDownViewResource method of the adapter and pass lass layout resource as parameter.

Run the application, the spinner opens dialog when click. It shows android:prompt text as title of the dialog which is Select Country.

Spinner

Custom Adapter for Spinner:

Customizing the spinner is same as ListView and GridView as done previously. Suppose if we want to show image and content in each item of the Spinner control. As you can see image below.

Spinner

Create an xml file in layout folder and name it custom_spinner_item.xml. Add ImageView and TextView control in it.

<?xml version="1.0" encoding="utf-8" ?>
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="horizontal" android:layout_width="match_parent"
        android:layout_height="match_parent">
    
    <imageview android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/imageView"
            android:layout_margin="4dp"
            android:layout_gravity="center_vertical" />

    <textview android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="New Text"
            android:layout_margin="4dp"
            android:textcolor="#000000"
            android:id="@+id/txtTitle" />

</linearlayout>

Now create new class and name it Country. Add name and flagId fields in it.

 public class Country {
    
    private String _name;
    private int _flagId;
    
    public Country(String name, int flagId)
    {
        _name = name;
        _flagId = flagId;
    }
    
    public String get_name() {
        return _name;
    }
    
    public void set_name(String _name) {
        this._name = _name;
    }
    
    public int get_flagId() {
        return _flagId;
    }
    
    public void set_flagId(int _flagId) {
        this._flagId = _flagId;
    }

 }

Once class is ready, create new class MySpinnerAdapter and extends it with BaseAdapter class, overrides its required methods.

public class MySpinnerAdapter extends BaseAdapter {
    
    Context _context;
    ArrayList<country> _list;
    
    public MySpinnerAdapter(Context context, ArrayList<country> list)
    {
        _context = context;
        _list = list;
    }
    
    @Override
    public int getCount() {
        return (_list == null)?0:  _list.size();
    }
    
    @Override
    public Object getItem(int i) {
        return _list.get(i);
    }
    
    @Override
    public long getItemId(int i) {
        return 0;
    }
    
    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        if(view == null)
        {
            LayoutInflater inflater = (LayoutInflater)_context.getSystemService(
                                                        Context.LAYOUT_INFLATER_SERVICE);
            view = inflater.inflate(R.layout.custom_spinner_item,viewGroup,false);
        }
        Country country = _list.get(i);
        
        TextView txtTitle = (TextView)view.findViewById(R.id.txtTitle);
        ImageView imgView = (ImageView)view.findViewById(R.id.imageView);
        txtTitle.setText(country.get_name());
        imgView.setImageResource(country.get_flagId());
        return view;
    }

}

In the getView method get R.layout.custom_spinner_item view using layout inflater. Set the image and country name to respective controls.

In the main activity code file create instance of MySpinnerAdapter class and set it to the Spinner control using setAdapter method.

 ArrayList<country> countries = new ArrayList<country>();

 countries.add(new Country("Belgium", R.drawable.belgium));
 countries.add(new Country("Denmark", R.drawable.denmark));
 countries.add(new Country("Italy", R.drawable.italy));
 countries.add(new Country("Netherlands", R.drawable.netherlands));
 countries.add(new Country("Romania", R.drawable.romania));
 countries.add(new Country("Switzerland", R.drawable.switzerland));
 countries.add(new Country("UnitedKingdom", R.drawable.unitedkingdom));

 MySpinnerAdapter arrayAdapter = new MySpinnerAdapter(getApplicationContext(),countries);
 
 Spinner spinner = (Spinner)findViewById(R.id.spinner3);
 spinner.setAdapter(arrayAdapter);

Get Selected Item

Spinner provide a getSelectedItem() method to get selected value. See the code below which shows selected item value in toast message.

Button btnSelected = (Button)findViewById( R.id.btnSelected);

btnSelected.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View view) {
        Spinner spinner = (Spinner) findViewById(R.id.spinner);
 
        String value1 = spinner.getSelectedItem().toString();
        String message = "Spinner 1 = " + value1;
        Toast.makeText(getApplicationContext(),
                       message, Toast.LENGTH_SHORT).show();
    }

});

Set Selected item

setSelection is use to select spinner item from code. It takes position as parameter.

 Spinner spinner = (Spinner) findViewById(R.id.spinner);
 spinner.setSelection(4);

On Item Selected Event Listener

Set item selected listener using setOnItemSelectedListener method and in onItemSelected method write your required code.

 Spinner spinner = (Spinner)findViewById(R.id.spinner2);

 spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {

            Spinner spinner = (Spinner)findViewById(R.id.spinner2);
            
            if(spinner.getSelectedItem() != null) {
                String country = spinner.getSelectedItem().toString();
                Toast.makeText(getApplicationContext(), "Country: " + 
                                   country, Toast.LENGTH_SHORT).show();
            }

        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {
        }

 });

Download Source Code

You can get the source code. Download Source Code

Other Topics

;