2012-09-22 128 views
3

在xml布局中,我有RadioGroup,Button1,Button2。当用户点击按钮1,几个单选按钮编程在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); 
       } 
      } 

问题是,这有时会工作得很好,但有时第一个单选按钮保持未删除。

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

回答

2

我的第一个猜测是,这个代码部分是坏:

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

你不能运行在一个视图中的孩子,而在同一时间 (rg.getChildCount(删除子)期间,将改变运行)

16

它真的很容易,你只要做到这一点:

rg.removeAllViews(); 

,因为我与工作了循环,但它并没有消除所有的单选按钮。 玩得开心:)

相关问题