RadioButton点击后状态切换前处理事件

项目内有个功能需求,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();
    }

}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值