在网上查了很多spinner,如何监听展开收起的状态,但是看了很多,只能看到展开,无法监听关闭,或者点击spinner外部区域关闭,也无法监听到。今天解决了,特此记录一下。
上图:
上代码:
自定义Spinner,实现其中的方法:CustomSpinner:
public class CustomSpinner extends Spinner {
private static final String TAG = "CustomSpinner";
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();
}
@Override
public boolean performClick() {
// register that the Spinner was opened so we have a status
// indicator for the activity(which may lose focus for some other
// reasons)
mOpenInitiated = true;
if (mListener != null) {
mListener.onSpinnerOpened();
}
return super.performClick();
}
public void setSpinnerEventsListener(OnSpinnerEventsListener onSpinnerEventsListener) {
mListener = onSpinnerEventsListener;
}
/**
* Propagate the closed Spinner event to the listener from outside.
*/
public void performClosedEvent() {
mOpenInitiated = false;
if (mListener != null) {
mListener.onSpinnerClosed();
}
}
/**
* A boolean flag indicating that the Spinner triggered an open event.
*
* @return true for opened Spinner
*/
public boolean hasBeenOpened() {
return mOpenInitiated;
}
@Override
public void onWindowFocusChanged(boolean hasWindowFocus) {
android.util.Log.d(TAG, "onWindowFocusChanged");
super.onWindowFocusChanged(hasWindowFocus);
if (hasBeenOpened() && hasWindowFocus) {
android.util.Log.i(TAG, "closing popup");
performClosedEvent();
}
}
}
在布局文件中直接替换掉原生Spinner,class中不要忘记更改初始化对象
/**
* 监听展开收起
*/
spinner.setSpinnerEventsListener(new CustomSpinner.OnSpinnerEventsListener() {
@Override
public void onSpinnerOpened() {
HQLog.i(TAG,"open");
}
@Override
public void onSpinnerClosed() {
HQLog.i(TAG,"close");
}
});
完毕。亲测有效!
只是一只老实的搬砖人..