Spinner's onItemSelected callback called twice after a rotation if non-zero position is selected

后端 未结 8 1040
执念已碎
执念已碎 2021-02-03 20:52

When I create my activity, I setup a Spinner, assigning it a listener and an initial value. I know that the onItemSelected callback is called automatically during a

8条回答
  •  悲&欢浪女
    2021-02-03 21:26

    This is what i did:

    Do a local variable

    Boolean changeSpinner = true;
    

    On the saveInstanceMethod save the selected item position of the spinner

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("ItemSelect",mySpinner.getSelectedItemPosition());
    }
    

    Then on the activity created get that int from savedInstanceState and if the int is != 0 then set the boolean variable on false;

    @Override
        public void onActivityCreated(Bundle savedInstanceState) {
    
        if (savedInstanceState!=null) {
            if (savedInstanceState.getInt("ItemSelect")!=0) {
               changeSpinner = false;
            }
        }
    
    }
    

    And for last on the OnItemSelected from the spinner do this

    mySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        public void onItemSelected(AdapterView parent,android.view.View v, int position, long id) {
            if (changeSpinner) {
               [...]
            } else {
               changeSpinner= true;
            }
        });
    

    So, the first time when is called is not going to do anything, just make the boolean variable true, and the second time is going to execute the code. Maybe not the best solution but it work.

提交回复
热议问题