当复选框改变状态时如何做某事? [英] How to do something when a checkbox change state?

查看:19
本文介绍了当复选框改变状态时如何做某事?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

    <CheckBox
        android:id="@+id/sprint_checkbox"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/sprint_game" />

    <CheckBox
        android:id="@+id/marathon_checkbox"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/marathon" />

    <CheckBox
        android:id="@+id/never_ending_checkbox"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/never_ending" />

我想要做的是检测"其中一个被选中,然后将另外两个设置为禁用",这样用户一次只能选择一个.我尝试使用.setOnCheckedChangeListener",但我不能这样做,有人可以帮我写一些代码吗?非常感谢各位!

What i want to do is "detect" when one of these is checked and then set the other two to "disable", so the user can select only one at time. I tried to use the ".setOnCheckedChangeListener", but i can't do that, can someone help me with some code? Thanks a lot guys!

推荐答案

这是您收到已检查更改通知的方式:

This is the way you are notified about checked changes:

CheckBox check = findViewById(R.id.sprint_checkbox);
check.setOnCheckedChangeListener(new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            //do stuff

        }
    });

您也可以让您的活动实现 OnCheckedChangeListener 接口,然后:

You can also let your activity implements the OnCheckedChangeListener interface and then:

CheckBox check1 = findViewById(R.id.sprint_checkbox);
CheckBox check2 = findViewById(R.id.marathon_checkbox); 
CheckBox check3 = findViewById(R.id.never_ending_checkbox);

check1.setOnCheckedChangeListener(this);
check2.setOnCheckedChangeListener(this);
check3.setOnCheckedChangeListener(this);

覆盖接口方法:

@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    switch(buttonView.getId()){
               case R.id.sprint_checkbox:
                 //do stuff
               break;
               case R.id.marathon_checkbox:
                 //do stuff
               break;
               case R.id.never_ending_checkbox:
                //do stuff
               break;

            }

}

这篇关于当复选框改变状态时如何做某事?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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