I have an Android Spinner and I want to listen the event when the user press "Back Key" when the spinner's select panel is showing.I have implement the OnItemSelectedListener ,but the onNothingSelected(AdapterView arg0) was not invoked when press back key.
I just want to listen the event when user select nothing( or the select panel disappear) .
Is there a correct way to do this?
Thanks!
Spinner s1 = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.colors, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s1.setAdapter(adapter);
s1.setOnItemSelectedListener(
new OnItemSelectedListener() {
public void onItemSelected(
AdapterView<?> parent, View view, int position, long id) {
showToast("Spinner1: position=" + position + " id=" + id);
}
public void onNothingSelected(AdapterView<?> parent) {
showToast("Spinner1: unselected");
}
});
This is a sample in Android 2.2 SDK,it's also not show "Spinner1: unselected" when the select panel disappear.
Another approach is to create a minimal custom spinner dropdown item, ie:
and then intercept onDetachedFromWindow():
You can finesse this if you use a custom ArrayAdapter to set only one of the dropdown items to do the callback, as well as setting suitable context for the callback, etc.
Depending on what you do inside the callback, you may want to post it as a runnable, so that the spinner is fully cleaned up before it does anything.
It looks like you won't be able to do what you want without extending the
Spinner
class. It seems thatSpinner
doesn't register anOnCancelListener
with theAlertDialog
it builds to display the items.Code from Spinner.java:
Also,
setSelection
is only called when an item in the dialog is clicked. This won't be called when the user presses the back button since that is anOnCancel
event.Extending
Spinner
will be a bit of a pain since you have to copy everything back toAdapterView
into your source from the android source since various member fields necessary for implementation are only exposed at the package level.