Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid having android spinner call itemselectedlistener when setting adapter?

It appears that android's Spinner class (and possibly ListView in general, although I don't know for sure) calls your OnItemSelectedListener's onItemSelected() method after you call setAdapter(), even if the user hasn't explicitly selected anything yet.

I can see how this would be useful in many situations, but there are times when I only want onItemSelected() to be called when an item is actually specifically selected.

Is there a way to control this behaviour and have Spinner NOT call onItemSelected() after setting the adapter?

like image 963
emmby Avatar asked Sep 03 '10 16:09

emmby


2 Answers

I haven't used this solution for very long yet so I'm not totally confident that it works as expected, but I've had luck so far with this workaround:

    spinner.setOnItemSelectedListener( new OnItemSelectedListener() {
        protected Adapter initializedAdapter = null;

        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

            // Always ignore the initial selection performed after setAdapter
            if( initializedAdapter !=parent.getAdapter() ) {
                initializedAdapter = parent.getAdapter();
                return;
            }

            ...
        }
    }

Is there a better way?

like image 109
emmby Avatar answered Nov 14 '22 23:11

emmby


Add listener to spinner like below:

spinner.post(new Runnable(){
    public void run()
    {
        spinner.setOnItemSelectedListener( new OnItemSelectedListener() {

            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                ...
            }
        }
    }
});
like image 21
spgodara Avatar answered Nov 14 '22 21:11

spgodara