In my android app, I have a Spinner, and I try to detect when an item is selected. I know this can be done using setOnItemSelectedListener() method, but what I don't understand is that this works fine:

((Spinner)findViewById(R.Id.mySpinner)).setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
    {
        // implement onItemClick here
    });

While this gives an error that the parameter is "not applicable" to Spinner:

((Spinner)findViewById(R.Id.mySpinner)).setOnItemSelectedListener(new MyOnItemSelectedListener());

Where MyOnItemSelectedListener is this, and it's a nested class in my MainActivity:

private class MyOnItemSelectedListener implements AdapterView.OnItemSelectedListener
{
    public MyOnItemSelectedListener() {}

    // implement onItemClick here
}

What I want to achieve is not just code that works - I already have that. It's code that's easily readable (with the real name of the things in my code and the structure of my MainActivity class, it is more readable using a nested class than an anonymous one).

How I understand java, these two should be the same thing essentially except one class has a name, and the other one doesn't.

1

There are 1 answers

1
Bhuvanesh BS On BEST ANSWER

In your code, You have used Id (R.Id.mySpinner) instead of id (R.id.mySpinner).

Both implementation in your code will definitely work.

Initialize Spinner:

Spinner spinner = new Spinner(getActivity());
spinner.setOnItemSelectedListener(new MySpinner());

Inner Class:

private class MySpinner implements AdapterView.OnItemSelectedListener{

    public MySpinner(){}

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

    }

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

    }
}

This is actually working fine for me. Check with your id and layout .