Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
265 views
in Technique[技术] by (71.8m points)

android spinner fire event when same item selection is made

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

@Override
    public void onItemSelected(AdapterView<?> parent, View arg1, int position,
            long arg3) {
    }

is called only when we different selection is made. My Purpose is to display a toast when any item is selected either the same item is reselected or different selection is made.

@Override
    public void onNothingSelected(AdapterView<?> parent) {

    }

above method does not solve my problem.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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. :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...