Spinner triggered by code?

Did you want to add listener to your spinner to do something, say, play one of the listed sounds? The problem is, when you enter this activity, your code will set the spinner as well. Guess what? It will trigger the listener as well!

Zordid at stackoverflow has a great work around.  Here is how:

  • keep the selected positions in field variables. (like currentPos1, currentPos2)
  • the listeners onItemSelectedListener() call a method like refreshMyResult() or whatever.
  • when setting positions programmatically, set the spinners and call your own refresh method manually right after that.

The refreshMyResult() method looks like this:

int newPos1 = mySpinner1.getSelectedItemPosition();

int newPos2 = mySpinner2.getSelectedItemPosition();

// only do something if update is not done yet

if (newPos1 != currentPos1 || newPos2 != currentPos2) {
              currentPos1 = newPos1;
        currentPos2 = newPos2;
         // do whatever has to be done to update things! 
         //This would be in the "old" listener 

Or, may be customize your spinner. For example, to play a sound in a spinner item, add a play button in the customized spinner item, and use listener for that.