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.

Advertisements

Android reverse engineering

thomascannon.net has some great tips on Android reverse engineering. I pulled an app from my phone, did reverse engineering on it and found the code is not even obfuscated…easy to read. Android is really weak in this regard. At least I should obfuscate.