如何开/关compount编程按钮,而不会影响在onCheckedChangeListener的onCheckedChanged() [英] How to on/off compount button programmatically without affecting the onCheckedChanged() in onCheckedChangeListener

查看:343
本文介绍了如何开/关compount编程按钮,而不会影响在onCheckedChangeListener的onCheckedChanged()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的应用程序使用 CompoundButton 。我叫了一个名为方法 newsLetterUpdate()中的 onCheckedChange()回调 CompoundButton.OnCheckedChangeListener 。我改变了 CompoundButton的选中状态编程,但 onCheckedChange()回调被调用。我想在 onCheckedChange()将只有当我打开了查看选中状态触发。
请建议我一个解决方案来改变复合按钮的状态没有 onCheckedChange()回调被调用。

I use a CompoundButton in my app. I call a method named newsLetterUpdate() in the onCheckedChange() callback of CompoundButton.OnCheckedChangeListener. I change the checked state of this CompoundButton programmatically, but the onCheckedChange() callback gets invoked. I want the onCheckedChange() to be triggered only if I switch the checked state on the View. Please suggest me a solution to change the state of compound button without the onCheckedChange() callback to be invoked.

推荐答案

方法4:使用自定义视图

import android.content.Context;
import android.util.AttributeSet;
import android.widget.Switch;

public class CustomSwitch extends Switch {


    private OnCheckedChangeListener mListener;

    public CustomSwitch(Context context) {
        super(context);
    }

    public CustomSwitch(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CustomSwitch(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public CustomSwitch(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @Override
    public void setOnCheckedChangeListener(OnCheckedChangeListener listener) {
        // Do not call supper method
        mListener = listener;
    }

    @Override
    public void setChecked(boolean checked) {
        super.setChecked(checked);

        if (mListener != null) {
            mListener.onCheckedChanged(this, checked);
        }
    }

    public void setCheckedProgrammatically(boolean checked) {
        // You can call super method, it doesn't have a listener... he he :)
        super.setChecked(checked);
    }

}

示例XML使用

<com.your.package.CustomSwitch
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

现在的想法是调用code中的方法 setCheckedProgrammatically setChecked 得到由名为Android的用户时,改变了复方按钮的状态

Now the idea is to call the method setCheckedProgrammatically in code. setChecked gets called by Android when users changes the state of the compund button

请注意,我使用一个开关,它扩展了复方按钮,你基本上可以使用同样的code上的任何其他(复选框,...)

Note that I'm using a switch, which extends the compund button, you can use basically the same code on any other (checkbox, ...)

这篇关于如何开/关compount编程按钮,而不会影响在onCheckedChangeListener的onCheckedChanged()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆