English 中文(简体)
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?

最佳回答

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?

问题回答

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) {

                ...
            }
        }
    }
});

I ve used the setTag and getTag methods, and created a resource id called "spinnerstate".

Then whenever I programmatically set the adapter, I set the "spinnerstate" tag to "init", and in the fired event, set it to "ready" and ignore the event. (note my code is Mono for Android se it will look different):

Set Adapter:

profileSpn.SetTag (Resource.Id.spinnerstate, "init");
profileSpn.Adapter = new ArrayAdapter (this, Android.Resource.Layout.SimpleSpinnerItem, items.ToArray ());

Item Selected event:

    string state = (string)((Spinner)sender).GetTag (Resource.Id.spinnerstate);
    if (state == "init") {
        ((Spinner)sender).SetTag (Resource.Id.spinnerstate, "ready");
        return;
    }

I agree that this is not desired behaviour in almost 100% of cases, and I don t think it s good design on the part of Google, but there you go.

I did similar things before, I used count value. Using parent adapter object is incomplete because it can be a problem when view is refreshed or getView() called again.

Therefore, I recommend that using array of counter.

At first, define array of count in adapter globally.

private int isInitializedView[];

And then initialize it on getView().

isInitializedView[position] = 0;

In the selection listener, do something that you want if it already initialized.

    holder.mySpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
            isInitializedView[position]++;
            if(isInitializedView[position] > 1) {
                // do someting that you want
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parentView) {}
    });

(Note that isInitializedView[position]++; can be come after if() routine, and only trigger event when this value is >0 . It s your choice.)

I had three spinner in my activity and all spinner adapter data has been filled at runtime(from web-service data after call from onCreate method). So it automatically call onItemSelected(AdapterView<?> parent, View view, int position, long id) method of spinner. I solved this issue by using onUserInteraction() method of activity check this method that user is interacting with spinner or not. if yes then perform the action else not

  1. Declare isUserIntract boolean variable globally

  2. in onItemSelected method use following procedure

    If(isUserIntract) {

    //perform Action

    } else{

    //not perform action

    }

  3. use below code in activity

@Override

public void onUserInteraction() {
super.onUserInteraction();
isUserIntract = true;
}




相关问题
Android - ListView fling gesture triggers context menu

I m relatively new to Android development. I m developing an app with a ListView. I ve followed the info in #1338475 and have my app recognizing the fling gesture, but after the gesture is complete, ...

AsyncTask and error handling on Android

I m converting my code from using Handler to AsyncTask. The latter is great at what it does - asynchronous updates and handling of results in the main UI thread. What s unclear to me is how to handle ...

Android intent filter for a particular file extension?

I want to be able to download a file with a particular extension from the net, and have it passed to my application to deal with it, but I haven t been able to figure out the intent filter. The ...

Android & Web: What is the equivalent style for the web?

I am quite impressed by the workflow I follow when developing Android applications: Define a layout in an xml file and then write all the code in a code-behind style. Is there an equivalent style for ...

TiledLayer equivalent in Android [duplicate]

To draw landscapes, backgrounds with patterns etc, we used TiledLayer in J2ME. Is there an android counterpart for that. Does android provide an option to set such tiled patterns in the layout XML?

Using Repo with Msysgit

When following the Android Open Source Project instructions on installing repo for use with Git, after running the repo init command, I run into this error: /c/Users/Andrew Rabon/bin/repo: line ...

Android "single top" launch mode and onNewIntent method

I read in the Android documentation that by setting my Activity s launchMode property to singleTop OR by adding the FLAG_ACTIVITY_SINGLE_TOP flag to my Intent, that calling startActivity(intent) would ...

From Web Development to Android Development

I have pretty good skills in PHP , Mysql and Javascript for a junior developer. If I wanted to try my hand as Android Development do you think I might find it tough ? Also what new languages would I ...

热门标签