如何处理检查和取消选中动态创建的复选框在android [英] How to handle check and uncheck dynamically created checkbox in android

查看:332
本文介绍了如何处理检查和取消选中动态创建的复选框在android的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了复选框使用循环,我想验证它。像我只想检查从复选框的3,当我按第四个,它应该显示一个警报,取消选中它。

i have created check boxes using loop and i want to validate it. Like i just want to check only 3 from the check boxes , when i press on the 4th one it should show an alert and uncheck it.

>

我可以得到警报,当我按4的一个,但它不是取消选中。

And i am able to get the alert when i press the 4the one but it is not unchecking.

任何人遇到此类问题,您是如何解决的?

anybody faced such issue and how did you solve it ?

推荐答案

int i;
for (i = 0; i < 20; i++) {
    CheckBox ch = new CheckBox(this);
    ch.setTag(Integer.valueOf(i));
    ch.setText("CheckBox " + i);
    ch.setChecked(false);
    ch.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                numChecked++;
            } else {
                numChecked--;
            }

            if (numChecked == 4) {
                buttonView.setChecked(false);
                numChecked--;
                // fourth one selected, show your dialog
            }
        }
    });
}

您还需要一个全局变量调用numChecked:

You will also need a global variable call numChecked:

int numChecked = 0;

您还需要在循环末尾添加一个.addView您的布局。

You will also need to add a .addView(ch) in the loop's end to add the CheckBoxes to your layout.

这篇关于如何处理检查和取消选中动态创建的复选框在android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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