项目内有个功能需求,RadioGroup
内有两个RadioButton
,点击后状态就会切换,但要求在点击某个RadioButton
之前,处理一些其他事情,再决定是否继续切换状态。比如网络连接状态,或者是否符合项目内业务逻辑等。
试过了OnCheckedChangeListener()
和onClickListener()
,方法会执行,但也会直接切换状态。
也想过用触摸事件拦截处理,但是太麻烦了。看了RadioButton
源码,发现复写了toggle()
方法,如图
在往上找,RadioButton
继承的CompoundButton
中,如图:
就是在performClick()
的时候调用直接调用了toggle()
方法去处理状态,所以直接复写toggle()
方法,添加监听接口,来判断是否继续切换状态即可
public class CommonRadioButton extends AppCompatRadioButton {
private handleBeforeClickListener listener;
//设置监听事件
public void setListener(handleBeforeClickListener listener) {
this.listener = listener;
}
public CommonRadioButton(Context context) {
super(context);
}
public CommonRadioButton(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CommonRadioButton(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public void toggle() {
if (listener != null) {
//先执行状态切换前的方法,然后根据返回值确定是否要截断切换状态
listener.handleBeforeClick();
//为false,则不截断,直接super的toggle,为true,则不需要处理,即不切换状态
if (!listener.handleBeforeClick()) super.toggle();
} else {
super.toggle();
}
}
//定义是否在切换状态前处理事件的接口
public interface handleBeforeClickListener {
boolean handleBeforeClick();
}
}