Android Spinner监听列表展开和收起状态

2023-12-15 12:35:34

Spinner只提供展开的监听,并未提供收起的监听

有时候需要监听Spinner列表的收起,比如根据展开收起的状态,改变右边显示的arrow图标的方向

我们可以通过自定义Spinner来监听列表的展开和收起

自定义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() {
        // 收起
    }
});

文章来源:https://blog.csdn.net/mqdxiaoxiao/article/details/135012618
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。