5

在 xml 布局中,我有 RadioGroup、Button1、Button2。当用户单击 button1 时,会在 RadioGroup 中以编程方式创建几个单选按钮(单选按钮的总数可能不同(pocet = 要创建的单选按钮的数量)。

    final RadioButton[] rb = new RadioButton[pocet];        
    RadioGroup rg = (RadioGroup) findViewById(R.id.MyRadioGroup);

    radiobuttonCount++;
    for(int i=0; i<pocet; i++){
        rb[i]  = new RadioButton(this);
        rb[i].setText("Radio Button " + radiobuttonCount);
        rb[i].setId(radiobuttonCount+i);            
        rb[i].setBackgroundResource(R.drawable.button_green);            
        rg.addView(rb[i]);            
    }

我尝试做的是:当用户从 RadioGroup 中选择 xy 项目时,我会将选定的值传递给 textview 并删除所有单选按钮。

出于删除目的,我使用:

        public void onCheckedChanged(RadioGroup rGroup, int checkedId)
        {
            RadioButton checkedRadioButton = (RadioButton)rGroup.findViewById(checkedId);
            boolean isChecked = checkedRadioButton.isChecked();
            if (isChecked)
            {
                RadioGroup rg = (RadioGroup)    findViewById(R.id.MyRadioGroup);                                        

                for (int i=0; i< rg.getChildCount(); i++){
                    rg.removeViewAt(i);
                }
            }

问题是这有时效果很好,但有时第一个单选按钮仍未删除。

PS稍后我想添加button2,它将为radiogroup提供不同的项目和不同的单选按钮数量。这就是为什么我需要在用户进行选择后删除所有单选按钮。

4

2 回答 2

28

它真的很简单,你只需这样做:

rg.removeAllViews();

因为我使用了 for 循环,但它没有删除所有 RadioButtons。玩得开心 :)

于 2013-03-15T18:28:23.560 回答
4

我的第一个猜测是这部分代码不好:

   for (int i=0; i< rg.getChildCount(); i++){
        rg.removeViewAt(i);
    }

您不能在同时移除孩子的同时越过一个视图的孩子(rg.getChildCount() 将在运行期间更改)

于 2012-09-22T20:25:21.403 回答