Search code examples
javaandroidspinner

How to get the spinner's id on the onItemSelected method?


My problem is : I want to have 3 different spinners, that displays the same type of object, and I want to be able to identify from which spinner I get the data, for example : In spinner 1, the user selected "potato" In spinner 2, the user selected "tomato" In spinner 3, the user selected "fries"

But I can only get "the user selected [...]", since I don't know how to tell from which spinner I got the data.

I was wondering if there was a way to do that on the onItemSelected(AdapterView parent, View view, int position, long id) method ?


Solution

  • Probably you have set a common listener for all the spinners, so you can distinguish which spinner was selected by checking parent.getId():

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        switch (parent.getId()){
            case R.id.spinner1:
                //your code here
                break;
            case R.id.spinner2:
                //your code here
                break;
            case R.id.spinner3:
                //your code here
                break;
        }
    }