简体   繁体   中英

Android Spinner On Re-Select Item

I have a spinner in my layout. currently, everything is working well but I need to do something when item reselected.

Is there any way to know the spinner item is reselected?.

public void onItemSelected(AdapterView<?> parent, View view,
        int pos, long id) {
    // An item was selected. You can retrieve the selected item using
}

public void onNothingSelected(AdapterView<?> parent) {
    // Another interface callback
}

I dont know if this idea can help you but you can try to create an ArrayList whit the pos or id values that you get in "onItemSelected", and inside of the method you read the ArrayList searching for it... something like this:

ArrayList<Integer> positions = new ArrayList();
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
   for(int posit : positions){
      if(posit==pos){
         //item reselected
      }
   }
   positions.add(pos);
}

I achieve reselection callback in onItemSelected by this custom spinner code. Ref: https://stackoverflow.com/a/11323043/9909365

import android.content.Context;
import android.util.AttributeSet;
import android.widget.Spinner;


/** Spinner extension that calls onItemSelected even when the selection is the same as its previous value */
public class NDSpinner extends Spinner {

    public NDSpinner(Context context)
    { super(context); }

    public NDSpinner(Context context, AttributeSet attrs)
    { super(context, attrs); }

    public NDSpinner(Context context, AttributeSet attrs, int defStyle)
    { super(context, attrs, defStyle); }

    @Override 
    public void setSelection(int position, boolean animate) {
        boolean sameSelected = position == getSelectedItemPosition();
        super.setSelection(position, animate);
        if (sameSelected) {
            // Spinner does not call the OnItemSelectedListener if the same item is selected, so do it manually now
            getOnItemSelectedListener().onItemSelected(this, getSelectedView(), position, getSelectedItemId());
        }
    } 

    @Override
    public void setSelection(int position) {
        boolean sameSelected = position == getSelectedItemPosition();
        super.setSelection(position);
        if (sameSelected) {
            // Spinner does not call the OnItemSelectedListener if the same item is selected, so do it manually now
            getOnItemSelectedListener().onItemSelected(this, getSelectedView(), position, getSelectedItemId());
        }
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM