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...
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:
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
I had the similar problem when I was implementing a spinner, I resolved it by getting the parent View and set Adapter-
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!