如何限制可以选中的复选框的数量? [英] How to limit number of checkboxes that can be checked?

查看:164
本文介绍了如何限制可以选中的复选框的数量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有4个复选框。我希望用户只选择其中的两个。如何设置限制?

I have 4 checkboxes. I want user to select only two of them. How to set that limit?

推荐答案

您可以轻松拥有一个存储多少目前复选框被选中的 INT 变量...那么任何时间 onCheckedChanged()被调用时,你检查该变量,如果它应该已经被检查第三复选框,只能把它重新设置为未选中...

You can easily have an int variable that stores how many checkboxes are currently checked... Then any time onCheckedChanged() is called, you check that variable and if it would already be a third checkbox to be checked, you just set it to unchecked again...

假设你开始与所有选中的复选框。所以,你做的:

Let's say you start with all the checkboxes unchecked. So you do:

int numberOfCheckboxesChecked = 0;

然后,设置 OnCheckChangedListener

checkbox1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked && numberOfCheckboxesChecked >= 2) {
            checkbox1.setChecked(false);
        } else {
            // the checkbox either got unchecked
            // or there are less than 2 other checkboxes checked
            // change your counter accordingly
            if (isChecked) {
                numberOfCheckboxesChecked++;
            } else {
                numberOfCheckboxesChecked--;
            }

            // now everything is fine and you can do whatever
            // checking the checkbox should do here
        }
    }
});

(我没有测试code,但它应该工作。)

(I have not tested the code, but it should work.)

这篇关于如何限制可以选中的复选框的数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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