Spinner item gets automatically selected upon entering activity. How do I avoid this?

user594720 picture user594720 · Mar 20, 2011 · Viewed 18.9k times · Source

I have a spinner in my Android app, and its onItemSelected() event automatically gets triggered upon entering the activity.

How do I avoid this?

Answer

thanhbinh84 picture thanhbinh84 · Jun 25, 2014

We can use a flag, and just enable it when the spinner is really touched.

private boolean isSpinnerTouched = false; 

spinner.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                isSpinnerTouched = true;
                return false;
            }
        });
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> adapter, View arg1,
                        int arg2, long arg3) {
                    if (!isSpinnerTouched) return;
                    // do what you want 
                    }
        });