获取java.lang.IllegalStateException:在使用RadioGroup时,您必须首先调用子视图的父视图中的removeView()

问题描述:

我已经使用RadioGroup来实现仅从动态创建的单选按钮中选择一个项目。获取java.lang.IllegalStateException:在使用RadioGroup时,您必须首先调用子视图的父视图中的removeView()

final LinearLayout firstRowTxtLayout = new LinearLayout(fContext); 
    firstRowTxtLayout.setLayoutParams(new LinearLayout.LayoutParams(
      LinearLayout.LayoutParams.WRAP_CONTENT, 
      LinearLayout.LayoutParams.WRAP_CONTENT)); 

    rbGroup.setLayoutParams(new LinearLayout.LayoutParams(
      LinearLayout.LayoutParams.WRAP_CONTENT, 
      LinearLayout.LayoutParams.WRAP_CONTENT)); 
    rbButton = new RadioButton(fContext); 
    rbButton.setLayoutParams(new LinearLayout.LayoutParams(
      LinearLayout.LayoutParams.WRAP_CONTENT, 
      LinearLayout.LayoutParams.WRAP_CONTENT)); 
    rbButton.setId(rbTagincreament); 
    rbGroup.addView(rbButton); 

and RadioGroup我已经在循环之外初始化了。并将RadioGroup视图添加到另一个版面

我再次更改了它(如下所示)。现在我得到单选按钮,但是我可以选择组中的每个按钮。

  private void createRadioButton(int num) { 
    Log.i("comVisa", "Num ==" + num); 

    rg = new RadioGroup(fContext); // create the RadioGroup 
    rg.setOrientation(RadioGroup.HORIZONTAL);// or RadioGroup.VERTICAL 

    rb = new RadioButton(fContext); 
    rb.setId(num++); 
    rg.addView(rb); // the RadioButtons are added to the radioGroup instead 
    // of the layout 
    firstRowTxtLayout.addView(rg);// you add the whole RadioGroup to the 
    // layout 
    rg.setOnCheckedChangeListener(new OnCheckedChangeListener() { 

     @Override 
     public void onCheckedChanged(RadioGroup group, int checkedId) { 


     } 
    }); 

} 

当我用来初始化的rg = new RadioGroup(fContext);外面我得到:

`IllegalStateException`. You must call removeView() on the child's parent first while using RadioGroup 

logcat的与代码行:

03-12 14:05:35.266: W/System.err(32734): at com.vipera.ts.gui.custom.comVisaApprovalList.createRadioButton(comVisaApprovalList.java:531) firstRowTxtLayout.addView(rg); 
03-12 14:05:35.266: W/System.err(32734): at com.vipera.ts.gui.custom.comVisaApprovalList.constructRow(comVisaApprovalList.java:459)createRadioButton(rbTagincreament++); 
03-12 14:05:35.271: W/System.err(32734): at com.vipera.ts.gui.custom.comVisaApprovalList.createTableLayout(comVisaApprovalList.java:411) 
03-12 14:05:35.271: W/System.err(32734): at com.vipera.ts.gui.custom.comVisaApprovalList.init(comVisaApprovalList.java:121) 
+1

是rbButton的父线性布局吗?如果是这样,你可能需要firstRowTxtLayout.removeView(rbButton) – eliteslayer 2013-03-11 18:04:07

+0

你在说什么循环? – 2013-03-11 18:07:11

rbButton目前正处于另一种观点认为,这就是为什么例外 。您必须请致电parent_of_rbButton.removeView(rbButton),然后才能将其添加到rbGroup

+1

感谢伟大的发布人 – Kris 2013-03-11 18:06:46