Showing posts with label Android Spinner selection. Show all posts
Showing posts with label Android Spinner selection. Show all posts

Thursday, September 11, 2014

Set the initial position in the spinner instead of the default initial position.(Android)


In your Activities onCreate() method do the following.

1. Get the spinner object
     Ex:
     Spinner obj =  findViewById(R.id.spinner);
2. Add listener to it
     obj.setOnItemSelectedListener(new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view,
                int position, long id) {
                      //TODO      
                }
      });

3. obj.setSelection(yourInitialPosition,false);
NOTE1: By calling this above method, Android make sure that the onItemSelected is not called 2 times. It will be called only once after the activity launches first time.

NOTE2: If we don't call the setSelection(int,boolean); at all then by default android calls onItemSelected with default position as 0.

NOTE3: if we call set setSelection(int) instead, then onItemSelected will be getting called twice.

public void setSelection (int position, boolean animate)

    Jump directly to a specific item in the adapter data.