Multiple spinners and onItemSelected

Use below code if you have multiple spinners in one activity and you are using onItemSelected override method

override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
         if (parent!!.id == R.id.spinner_1) {
            // first spinner selected
         } else if (parent!!.id == R.id.spinner_2) {
            // second spinner selected
         }
    }

either you can use switch case


At first in onCreate :

Spinner cit_for_bus,  bus_number;
cit_for_bus = (Spinner) findViewById(R.id.cit_for_bus);
bus_number = (Spinner) findViewById(R.id.bus_number);
cit_for_bus.setOnItemSelectedListener(this);
bus_number.setOnItemSelectedListener(this);

don't forget to use : you have to bind/tie spinners to onItemSelected

cit_for_bus.setOnItemSelectedListener(this);
bus_number.setOnItemSelectedListener(this);

and use implement for class :

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener

outSide of onCreate use this :

@Override
    public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
        if (adapterView.getId() == R.id.cit_for_bus) {

            Toast.makeText(getApplicationContext(), adapterView.getId() + "/ " + adapterView.getCount() + "/" + adapterView.getSelectedItem(), Toast.LENGTH_LONG).show();

        } else if (adapterView.getId() == R.id.bus_number) {
            Toast.makeText(getApplicationContext(), adapterView.getId() + "/ " + adapterView.getCount() + "/" + adapterView.getSelectedItem(), Toast.LENGTH_LONG).show();

        }
    }

use:

switch(parent.getId()) {
    ...
}

instead is what you need. The view in your parameter is the actual 'row' (i.e. the clicked child of spinner item), and the parent is the actual 'spinner' that you are after.


Spinner is a subclass of AdapterView. The parent object passed into the method is the spinner in which the item was selected.