Friday, June 1, 2012

How to avoid spinner listener to get fire before Adapter is set in android?


Solution
1.    in onCreate(), count how many Spinner (or Spinner) widgets you have in the view. (mSpinnerCount)
2.    in onItemSelected(), count how often it has triggered. (mSpinnerInitializedCount)
3.    when (mSpinnerInitializedCount < mSpinnerCount) == false, then execute the code meant for the user

public class myActivity extends Activity implements OnItemSelectedListener
{
    //this counts how many Spinner's are on the UI
    private int mSpinnerCount=0;
    //this counts how many Spinner's have been initialized
    private int mSpinnerInitializedCount=0;
    //UI reference
    private Spinner mSpinner;


    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.myxmllayout);

        //get references to UI components
        mSpinner = (Spinner) findViewById(R.id.myspinner);

        //trap selection events from spinner
        mSpinner.setOnItemSelectedListener(this);

        //trap only selection when no flinging is taking place
        mSpinner.setCallbackDuringFling(false);

        //
        //do other stuff like load images, setAdapter(), etc
        //

        //define how many Spinner's are in this view
        //note: this could be counted dynamically if you are programmatically creating the view
        mSpinnerCount=1;
    }


    public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
    {
        if (mSpinnerInitializedCount < mSpinnerCount)
        {
            mSpinnerInitializedCount++;
        }
        else
        {
            //only detect selection events that are not done whilst initializing
            Log.i(TAG, "selected item position = " + String.valueOf(position) );
        }
    }
}

Why this works
this solution works because the Spinner finishes initialization long before a user is physically able to make a selection.

No comments:

Post a Comment