Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set Spinner item without onItemSelected getting called

Is it possible to change the selected spinner position to something without having the onItemSelected method getting called?

basically what I am trying to do is go back to the previously selected item in the spinner since one of them shows a dialog when selected. When the user hits the back button the spinner still shows that they are on the position that shows the dialog when it has been dismissed.

So is there a way to either keep it from getting called when reverting back using spinner.setSelection(position) or is there a way to keep the position that shows the dialog from staying selected?

public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
    switch(arg2){
    case 0:

        previousSelection = 1;
        mNavButtonClick.onNavButtonClick(1);

        break;
    case 1:
        previousSelection = 2;
        mNavButtonClick.onNavButtonClick(2);

        break;
    case 2:
        previousSelection = 3;
        mNavButtonClick.onNavButtonClick(3);
        break;
    case 3:
        previousSelection = 4;
        mNavButtonClick.onNavButtonClick(4);
        break;
    case 4:
        previousSelection = 5;
        mNavButtonClick.onNavButtonClick(5);
        break;
    case 5:
                    //this case shows the dialog
        mNavButtonClick.onNavButtonClick(6);
        break;
    default:
        break;
    }
}

dialog is shown, user clicks the back button to close dialog and in the onDismiss I call

spinner.setSelection(previousSelection);

to go back to the previous selection but this re-creates the view again which I dont want since I am already on the view I just want to show that I am on the view in the spinner

like image 422
tyczj Avatar asked May 08 '13 18:05

tyczj


2 Answers

Its very simple!

spinner.adapter = adapter
spinner.setSelection(pos) // whatever integer!
spinner.setTag("bug init")
spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
        override fun onNothingSelected(p0: AdapterView<*>?) = Unit
        override fun onItemSelected(p0: AdapterView<*>?, p1: View?, position: Int, p3: Long) {

        if (spinner.getTag().equals("bug init")) {
            spinner.setTag("okay, no more bug")
        }
        else {
            whateverMethod()
        }
}

When you put method call in spinner listener, it will very risk that method will executing self because of bug of init still exist in 2020!

So, this is how i solved it!

like image 115
Jetwiz Avatar answered Nov 15 '22 14:11

Jetwiz


AFAIK, there is no way to stop the function being called. BUT, you can choose to NOT execute the code in the function using a simple if (when you use setSelection) Check out the accepted answer here:

Undesired onItemSelected calls

like image 1
Vedavyas Bhat Avatar answered Nov 15 '22 14:11

Vedavyas Bhat