19

This is driving me nuts since it's something I've done before but can't figure out why it isn't working now...

I've got a menu button, implemented in the usual way via a menu.xml file and the onOptionsItemSelected method with a switch in it, that creates and displays a spinner.

I've added the setOnItemSelectedListener, but it never seems to trigger. The spinner appears, I pick an option or back out, neither onItemSelected or onNothingSelected are called.

Here is all the code between the "case" and "return true" of the menu-button-handling switch statement. (topThis is a variable referring to the context of the activity - works fine for all other toasts in the app)

String[] widgetModes = {"Mode 1", "Mode2"};
ArrayAdapter<String> widgetModeAdapter = new ArrayAdapter<String> (this, android.R.layout.simple_spinner_item, widgetModes);
widgetModeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

Spinner widgetModeSpinner = new Spinner(this);
widgetModeSpinner.setAdapter(widgetModeAdapter);
widgetModeSpinner.setPrompt("Choose Widget Mode");

widgetModeSpinner.setOnItemSelectedListener(new OnItemSelectedListener() 
{
    @Override
    public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) 
    {
        Toast.makeText(topThis, "derp", Toast.LENGTH_LONG).show();
    }

    @Override
    public void onNothingSelected(AdapterView<?> parentView) 
    {
        Toast.makeText(topThis, "herf", Toast.LENGTH_LONG).show();
    }
});

widgetModeSpinner.performClick();

Any ideas? I vaguely suspect that the fact I'm creating the Spinner programmatically is the problem...

HitOdessit
  • 7,198
  • 4
  • 36
  • 59
Greg
  • 309
  • 1
  • 4
  • 16
  • perhaps try parentView.getContext() ? Do you not need to add it somewhere to the UI? - this may mean that UI interaction events like item selection aren't getting passed to the Spinner. – Jems Feb 07 '11 at 16:38
  • 1
    Thanks for the tip - ended up implementing something along those lines. Added an invisible spinner to the layout, moved everything except the performClick out of the menu method and into one called in onCreate. Seems to ensure that the listener is "attached" to the currently inflated layout, or some such. The code's position in relation to setContentView(R.layout.main); is important... – Greg Feb 08 '11 at 09:26
  • 1
    I think the fact that the rest of my code involves occasionally reinflating the layout (using setContentView(R.layout.main);) also causes problems... listeners no longer attached if not set again after layout is reinflated. – Greg Feb 08 '11 at 09:32
  • 1
    You should try with a simple Log. i("tag", "message" ) ; instead of Toast to confirm its not your Context topThis causing it? – TouchBoarder Oct 05 '12 at 15:02
  • You are defining a onItemSelectedListener but are calling a synthetic performClick().... Maybe you should override onItemClicked() instead? – Shark Dec 07 '12 at 16:49
  • @Shark there is no onItemClickListener for Spinners. – A Person Apr 13 '13 at 17:08
  • @Siidheesh onItemSelected() in that case... – Shark Apr 15 '13 at 16:19
  • Your comment about the layout reinflating helped me in a case where I was trying to add spinners to ListView items that keep redrawing. I changed to PopupMenus, which ended up being much simpler. – arlomedia Aug 19 '14 at 21:08
  • performClick is probably causing problem. It returns first item and after selecting item it returns InputEventReceiver: Attempted to finish an input event but the input event receiver has already been disposed. Haven't find work around yet. – LadyWoodi Mar 11 '16 at 08:59
  • **Workaround** : I had to add spinner to xml (don't forget `android:spinnerMode="dialog"` and you can set 0 size params) and change = new Spinner(this); to ` = (Spinner) findViewById(R.id.dialog_spinner);` – LadyWoodi Mar 11 '16 at 09:38

4 Answers4

14

I had the similar problem when I was implementing a spinner, I resolved it by getting the parent View and set Adapter-

spinner1 =(Spinner)findViewById(R.id.spinner1);
spinner1.setAdapter(BindSpinner("ProgramMaster",cols,null,true,""));
spinner1.setOnItemSelectedListener(new OnItemSelectedListener() 
{
protected Adapter initializedAdapter=null;
    @Override
    public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) 
    {
        if(initializedAdapter !=parentView.getAdapter() ) {
            initializedAdapter = parentView.getAdapter();
           return;
        }

        String selected = parentView.getItemAtPosition(position).toString();

        if(abc.equals("Select") && !selected.equals("Select"))
        {
            do something
        }

        else 
        {
            Do something
        }
        textQualification=selected;
        SearchUpdated("Qualification");
    }

    @Override
    public void onNothingSelected(AdapterView<?> parentView) {
        // your code here
    }
});
Skurmedel
  • 21,515
  • 5
  • 53
  • 66
JNI_OnLoad
  • 5,472
  • 4
  • 35
  • 60
6

Remember that you can't re-select the same spinner item, it always sets the first item as selected if you are not adding some custom code to handle the spinner selection.

For the Toast not showing, I would suggest to always use the "MyActivity.this" as your context when creating a Toast inside a listener interface like this:

spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        /**
         * Called when a new item is selected (in the Spinner)
         */
         public void onItemSelected(AdapterView<?> parent, View view, 
                    int pos, long id) {
                // An spinnerItem was selected. You can retrieve the selected item using
                // parent.getItemAtPosition(pos)

                Toast.makeText(MyActivity.this, "Hello Toast",Toast.LENGTH_SHORT).show();

            }

            public void onNothingSelected(AdapterView<?> parent) {
                // Do nothing, just another required interface callback
            }

    }); // (optional)

And the .show() at the end is easy to forget sometimes;)

TouchBoarder
  • 6,422
  • 2
  • 52
  • 60
5

Actually, if your spinner visibility is set to gone then it will trigger the click of it when you call performclick() method but it will not trigger its setOnItemSelectedListener so you need to change the visibility then it will work

Mehroz Munir
  • 2,248
  • 1
  • 18
  • 16
2

I know the question is a bit old, but in case you are waiting for a AsyncTask callback, make sure that you let your adapter know of the data changes by calling notifyDataSetChanged() on the callback thread!

@Override
public void onPostExecute(String result) {
   ///do something with your data  
   spinnerArrayAdapter.notifyDataSetChanged();
}