Avoid onItemSelected firing when spinner (or gallery) instantiated

Solutions (eg. see here) include

  • counting the number of times the listener has fired
  • usign a boolean to treat the first firing differently
  • using a runnable to delay registering the listener.

What seemed most appropriate (and simple) for me was

  • declare an integer variable as a default (or last used and saved in preferences) value
  • set that value to the spinner before¬†registering the listener
  • in the¬†onItemSelected check whether the spinner value equals the value you assigned before running any further code.

 

spinner1.setSelection(myDefault);	//set default (or last selection)
spinner1.setOnItemSelectedListener(this);
.....
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
if (arg2 != myDefault) {
	myDefault = arg2;
        do further code
This entry was posted in Android. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *