znl_12 2013-04-08 07:28 采纳率: 0%
浏览 7169
已采纳

如何动态的添加 Radiobutton ?

XML 文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" 
android:id="@+id/sl"
>
<RadioGroup
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:id="@+id/rgc">
 </RadioGroup>
</LinearLayout>

Java 文件:

LinearLayout l1;
RadioGroup rg;
RadioButton rb[];
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    l1=(LinearLayout)findViewById(R.id.sl);
    rg=(RadioGroup)findViewById(R.id.rgc);
    rb=new RadioButton[4];
    for(int i=0;i<4;i++){
        rb[i]=new RadioButton(this);
        rb[i].setLayoutParams(new LinearLayout.LayoutParams(60,30));
        rb[i].setText(i+"aaaaaa");
        rg.addView(rb[i]);
    }
    l1.addView(rg);
}

我添加了Radiobutton,运行上面的代码后,出现异常:"this specified child already has a parent",代码有什么问题吗?

  • 写回答

2条回答

  • usniyo 2013-04-08 09:16
    关注

    findViewById()得到的是一个已经存在的view,你再把它放入其父view一次,自然会抛该view已存在的异常,除非你先把它从它父view中移除,但这不是你想要的吧?所以你得通过new RadioGroup(...)新生成一个,再添加。就像你new RadioButton(...)后再add一样。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?