How can you set the event listener for a Spinner when the selected item changes?
Basically what I am trying to do is something similar to this:
spinner1.onSelectionChange = handleSelectionChange;
void handleSelectionChange(Object sender){
//handle event
}
take a global variable for current selection of spinner:
Find your spinner name and find id then implement this method.
It doesn't matter will you set OnItemSelectedListener in onCreate or onStart - it will still be called during of Activity creation or start (respectively).
So we can set it in onCreate (and NOT in onStart!).
Just add a flag to figure out first initialisation:
then in onCreate (or onCreateView) just:
Brilliant the above by Stefan Klumpp also helped me a lot. Thank you. I am a newbie and the "@Override"s in it caused an error about "must override a Super class method of the same name". Eclipse suggested I should remove the Overrides. When I did this, it worked. Please don't ask me how or why.
One trick I found was putting your setOnItemSelectedListeners in onWindowFocusChanged instead of onCreate. I haven't found any bad side-effects to doing it this way, yet. Basically, set up the listeners after the window gets drawn. I'm not sure how often onWindowFocusChanged runs, but it's easy enough to create yourself a lock variable if you are finding it running too often.
I think Android might be using a message-based processing system, and if you put it all in onCreate, you may run into situations where the spinner gets populated after it gets drawn. So, your listener will fire off after you set the item location. This is an educated guess, of course, but feel free to correct me on this.
You can implement
AdapterView.OnItemSelectedListener
class in your Activity.And then use the below line within
onCreate()
Then override these two methods: