Android的动态生成的单选按钮不取消选中一次编程setChecked [英] Android dynamically generated radio buttons not unchecking once setChecked programmatically

查看:270
本文介绍了Android的动态生成的单选按钮不取消选中一次编程setChecked的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不能让下面的动态生成的单选按钮来取消当我在同一个RadioGroup中单击其他单选按钮。

I can't get the below dynamically generated RadioButtons to uncheck when I click on other RadioButton in the same RadioGroup.

我甚至使出写我自己的处理程序,清除RadioGroup中(如下图),并尝试另一个让所有单选按钮.setChecked(假),但是这仍然没有清楚,我在PopulateAccessPoints setChecked的单选按钮。

I have even resorted to writing my own handler that clears the RadioGroup (below), and tried another that make all RadioButtons .setChecked(false) but this still does not clear the RadioButton that I setChecked in PopulateAccessPoints.

任何想法?

RelativeLayout rlaAccessPoints;
RadioGroup rg;

public void onRadioButtonClicked(View view) {
// Is the button now checked?
RadioButton rd = (RadioButton)view;
rg.clearCheck();
rd.setChecked(true);
}


private void PopulateAccessPoints(List<clsAccessPoint> accessPoints){
rg = new RadioGroup(this);

for (clsAccessPoint acp :  accessPoints) {
    RadioButton rd = new RadioButton(this);
    rd.setText(acp.ID + ": " + acp.Name);

    rd.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            onRadioButtonClicked(v);
        }
    });

    rg.addView(rd);
}

rlaAccessPoints.addView(rg);

for (int i = 0; i <= rg.getChildCount() - 1; i++){
    RadioButton rd = new RadioButton(this);
    rd = (RadioButton)rg.getChildAt(i);

    String rdText = rd.getText().toString();
    int colonPos = rdText.indexOf(":");
    rdText = rdText.substring(0, colonPos).toString();
    if (Settings.AccessPointID.equals(rdText)){
        //rg.check(i);
        rd.setChecked(true);
    }
}

}

编辑:我下面贴有更加简洁code答案;请看看这个吧。

I posted an answer below with much more concise code; please look at that instead.

推荐答案

在code我加来尝试解决这个问题是混淆了大家;抱歉。

The code I added to try to fix this is confusing everyone; sorry.

原来的code是:

RelativeLayout rlaAccessPoints;
RadioGroup rg;

private void PopulateAccessPoints(List<clsAccessPoint> accessPoints){
rg = new RadioGroup(this);

for (clsAccessPoint acp :  accessPoints) {
    RadioButton rd = new RadioButton(this);
    rd.setText(acp.ID + ": " + acp.Name);

    rg.addView(rd);

    if (Settings.AccessPointID.equals(acp.ID)){
        rd.setChecked(true);
    }
}

rlaAccessPoints.addView(rg);
}

这显示相同的不正确的行为(即我设定编程不是取消设置,当我在同一个RadioGroup中点击另一个单选按钮)。

This shows the same incorrect behaviour (the RadioButton that I set programatically not being unset when I click on another in the same RadioGroup).

请参阅本code来代替。这是唯一适用code;没有自定义事件处理程序等。

Please refer to this code instead. This is the only applicable code; there is no custom event handlers etc.

这篇关于Android的动态生成的单选按钮不取消选中一次编程setChecked的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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