android spinner fire event when same item selection is made

前端 未结 5 1512
迷失自我
迷失自我 2020-12-10 12:25

I want to fire a event when the same item is selected in spinner. Method

@Override
    public void onItemSelected(AdapterView parent, View arg1, int         


        
5条回答
  •  南方客
    南方客 (楼主)
    2020-12-10 12:51

    i have found that old selection is kept at variable called mOldSelectedPosition in the hierarcy of the spinner. Spinner is using this value to check if the same item selected or not , and if it is the same , it ignores. If we dont wanna ignore this What i did is some dirty code using reflection.

    package com.aradiom.amc.nativecomponents;
    
    import java.lang.reflect.Field;
    
    import android.content.Context;
    import android.util.Log;
    import android.widget.Spinner;
    
    public class SpinnerTrigger extends Spinner {
    
    public SpinnerTrigger(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
    }
    
    @Override
    public void setSelection(int position, boolean animate) {
        ignoreOldSelectionByReflection();
        super.setSelection(position, animate);
    }
    
    private void ignoreOldSelectionByReflection() {
        try {
            Class c = this.getClass().getSuperclass().getSuperclass().getSuperclass();
            Field reqField = c.getDeclaredField("mOldSelectedPosition");
            reqField.setAccessible(true);
            reqField.setInt(this, -1);
        } catch (Exception e) {
            Log.d("Exception Private", "ex", e);
            // TODO: handle exception
        }
    }
    
    @Override
    public void setSelection(int position) {
        ignoreOldSelectionByReflection();
        super.setSelection(position);
    }
    
    }
    

    This class will always invalidate the oldselection value , so that every time on click event gets triggered. It may not be perfect solution. Use with caution. :)

提交回复
热议问题