java - Spinner onItemSelected() executes when it is not suppose to -


possible duplicate:
android spinner onitemselected called erroneously (without user action on opening spinner)

does know how prevent onitemselected() (onitemselectedlistener interface) method running when layout instantiated? need know if there way because want keep how instantiate layout separate listener.

i have tried creating if statement set false around code inside of overridden method, there no way of knowing when set true because overridden method runs after oncreate(), onstart(), , onresume() methods everytime.

i have not found clear cut answers on this. clear cut solutions appreciated.

david, here tutorial wrote problem...

problem statement

an undesirable onitemselected() triggered whilst gallery (or spinner) initializing. means code prematurely executed; code intended execute when user physically makes selection.

solution

  1. in oncreate(), count how many gallery (or spinner) widgets have in view. (mgallerycount)
  2. in onitemselected(), count how has triggered. (mgalleryinitializedcount)
  3. when (mgalleryinitializedcount < mgallerycount) == false, execute code meant user

code example

public class myactivity extends activity implements onitemselectedlistener {     //this counts how many gallery's on ui     private int mgallerycount=0;      //this counts how many gallery's have been initialized     private int mgalleryinitializedcount=0;      //ui reference     private gallery mgallery;       @override     public void oncreate(bundle savedinstancestate)     {          super.oncreate(savedinstancestate);         setcontentview(r.layout.myxmllayout);          //get references ui components         mgallery = (gallery) findviewbyid(r.id.mygallery);          //trap selection events gallery         mgallery.setonitemselectedlistener(this);          //trap selection when no flinging taking place         mgallery.setcallbackduringfling(false);          //         //do other stuff load images, setadapter(), etc         //          //define how many gallery's in view         //note: counted dynamically if programmatically creating view         mgallerycount=1;      }       public void onitemselected(adapterview<?> parent, view view, int position, long id)     {          if (mgalleryinitializedcount < mgallerycount)         {             mgalleryinitializedcount++;         }         else         {             //only detect selection events not done whilst initializing             log.i(tag, "selected item position = " + string.valueof(position) );         }      }  } 

why works

this solution works because gallery finishes initialization long before user physically able make selection.


Comments

Popular posts from this blog

php - What is the difference between $_SERVER['PATH_INFO'] and $_SERVER['ORIG_PATH_INFO']? -

fortran - Function return type mismatch -

queue - mq_receive: message too long -