天天看点

android Sipnner点击相同Item不响应OnItemSelected事件

原因:

1.下拉列表Sipnner点击相同Item不会响应(也就是spinner的OnItemSelectedListener只在第一次点击调用,其余重复点击不再响应)是因为Spinner的父类AbsSpinner的源代码为:

 voidsetSelectionInt(int position, boolean animate) {

       if (position != mOldSelectedPosition) {

           mBlockLayoutRequests = true;

           int delta  = position -mSelectedPosition;

           setNextSelectedPositionInt(position);

           layout(delta, animate);

           mBlockLayoutRequests = false;

       }

    }

解决办法:自定义一个Spinner控件,代码如下:

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

public class MySpinner extends Spinner {

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

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

	public MySpinner(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) {
			getOnItemSelectedListener().onItemSelected(this, getSelectedView(),
					position, getSelectedItemId());
		}
	}

	@Override
	public void setSelection(int position) {
		boolean sameSelected = position == getSelectedItemPosition();
		super.setSelection(position);
		if (sameSelected) {
			getOnItemSelectedListener().onItemSelected(this, getSelectedView(),
					position, getSelectedItemId());
		}
	}
}
           

在自己代码里面使用MySpinner控件就可以了