Spinner只提供展开的监听,并未提供收起的监听
有时候需要监听Spinner列表的收起,比如根据展开收起的状态,改变右边显示的arrow图标的方向
我们可以通过自定义Spinner来监听列表的展开和收起
public class CustomSpinner extends Spinner {
private OnSpinnerEventsListener mListener;
private boolean mOpenInitiated = false;
public CustomSpinner(Context context, AttributeSet attrs, int defStyleAttr, int mode) {
super(context, attrs, defStyleAttr, mode);
}
public CustomSpinner(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public CustomSpinner(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomSpinner(Context context, int mode) {
super(context, mode);
}
public CustomSpinner(Context context) {
super(context);
}
public interface OnSpinnerEventsListener {
void onSpinnerOpened();
void onSpinnerClosed();
}
public void setSpinnerEventsListener(OnSpinnerEventsListener onSpinnerEventsListener) {
mListener = onSpinnerEventsListener;
}
@Override
public boolean performClick() {
mOpenInitiated = true;
if (mListener != null) {
mListener.onSpinnerOpened();
}
return super.performClick();
}
public void performClosedEvent() {
mOpenInitiated = false;
if (mListener != null) {
mListener.onSpinnerClosed();
}
}
public boolean hasBeenOpened() {
return mOpenInitiated;
}
@Override
public void onWindowFocusChanged(boolean hasWindowFocus) {
super.onWindowFocusChanged(hasWindowFocus);
if (hasBeenOpened() && hasWindowFocus) {
performClosedEvent();
}
}
}
customSpinner.setSpinnerEventsListener(new CustomSpinner.OnSpinnerEventsListener() {
@Override
public void onSpinnerOpened() {
// 展开
}
@Override
public void onSpinnerClosed() {
// 收起
}
});