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

后端 未结 8 1036
执念已碎
执念已碎 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:22

    Try this:

    boolean mConfigChange = false;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        mConfigChange = false;
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mainf);
    
        Log.i("SpinnerTest", "Activity onCreate");
        ArrayAdapter adapter = ArrayAdapter.createFromResource(this, R.array.colors,
                android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        ((Spinner) findViewById(R.id.spin)).setAdapter(adapter);
    
         ((Spinner) findViewById(R.id.spin)).setSelection(2);
        ((Spinner) findViewById(R.id.spin)).setOnItemSelectedListener(this);
    
    }
    
    @Override
    protected void onResume() {
        mConfigChange = true;
        super.onResume();
    }
    
    @Override
    public void onItemSelected(AdapterView spin, View selview, int pos, long selId) {
        if (!mConfigChange)
            Log.i("Test", "spin:" + spin + " sel:" + selview + " pos:" + pos + " selId:" + selId);
        else
            mConfigChange = false;
    }
    

提交回复
热议问题