如何以编程方式删除单选按钮项目

Rad*_*iak 5 android dynamic button radio

在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]);            
    }
Run Code Online (Sandbox Code Playgroud)

我尝试做的是:当用户从RadioGroup中选择xy项时,我会将所选值传递给textview并删除所有radioButtons.

为了删除目的,我使用:

        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);
                }
            }
Run Code Online (Sandbox Code Playgroud)

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

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

M09*_*009 23

它真的很容易,你只需这样做:

rg.removeAllViews();
Run Code Online (Sandbox Code Playgroud)

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


dor*_*506 4

我的第一个猜测是这部分代码很糟糕:

   for (int i=0; i< rg.getChildCount(); i++){
        rg.removeViewAt(i);
    }
Run Code Online (Sandbox Code Playgroud)

您不能在删除子视图的同时运行一个视图的子视图(rg.getChildCount() 将在运行过程中发生变化)