Odd Android Spinner behavior

后端 未结 1 1569
死守一世寂寞
死守一世寂寞 2020-12-22 05:23

This is the code to populate my spinner.

The code:

String[] rcs = new String[review_cycles.length];
for (int i = 0; i < review_cycles.length; i++         


        
1条回答
  •  被撕碎了的回忆
    2020-12-22 05:49

    When I select a value from the spinner, the code is executed twice.

    As I reminded you in the comments, Spinners call onItemSelected() when they load the default value. This feature is useful when you know about it, but since it is not what the average developer expects it is problematic as well.

    The Spinner will also call onItemSelected() when the user re-selects the current value... When I want to avoid both of these false alarms I use something like this:

    spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
        int previous = -1;
        @Override
        public void onItemSelected(AdapterView parent, View view, int position, long id) {
            if(previous != position && previous < -1) {
                Log.v("Example", "Selected: " + position);
                // Do something
            }
            previous = position;
        }
    
        @Override
        public void onNothingSelected(AdapterView parent) {}
    });
    

    0 讨论(0)
提交回复
热议问题