Setting a spinner onClickListener() in Android
Solution 1:
Here is a working solution:
Instead of setting the spinner's OnClickListener, we are setting OnTouchListener and OnKeyListener.
spinner.setOnTouchListener(Spinner_OnTouch);
spinner.setOnKeyListener(Spinner_OnKey);
and the listeners:
private View.OnTouchListener Spinner_OnTouch = new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
doWhatYouWantHere();
}
return true;
}
};
private static View.OnKeyListener Spinner_OnKey = new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
doWhatYouWantHere();
return true;
} else {
return false;
}
}
};
Solution 2:
Whenever you have to perform some action on the click of the Spinner in Android, use the following method.
mspUserState.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
doWhatIsRequired();
}
return false;
}
});
One thing to keep in mind is always to return False while using the above method. If you will return True then the dropdown items of the spinner will not be displayed on clicking the Spinner.
Solution 3:
Personally, I use that:
final Spinner spinner = (Spinner) (view.findViewById(R.id.userList));
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
userSelectedIndex = position;
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});