Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spinner:How to know whether item selection was changed programmatically or by a user action through UI

Tags:

android

I have code that runs OnItemSelectedListener event of spinner. So when I am in the method:

public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
    // I want to do something here if it's a user who changed the the selected item
}

...how can I know whether the item selection was done programmatically or by a user action through the UI?

like image 240
con_9 Avatar asked May 14 '10 09:05

con_9


1 Answers

I don't know that this can be distinguished from within the method. Indeed, it is a problem that a lot of people are facing, that onItemSelected is fired when the spinner is initiated. It seems that currently, the only workaround is to use an external variable for this.

private Boolean isUserAction = false;

...

public void onItemSelected( ... ) {

    if( isUserAction ) {
       // code for user initiated selection
    } else {
       // code for programmatic selection
       // also triggers on init (hence the default false)
    }

    // reset variable, so that it will always be true unless tampered with
    isUserAction = true;
}

public void myButtonClick( ... ) {
    isUserAction = false;
    mySpinner.setSelectedItem ( ... );
}
like image 147
David Hedlund Avatar answered Sep 29 '22 10:09

David Hedlund