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",代碼有什麼問題嗎?
findViewById()
得到的是一個已經存在的view,你再把它放入其父view一次,自然會拋該view已存在的異常,除非你先把它從它父view中移除,但這不是你想要的吧?所以你得通過new RadioGroup(...)
新生成一個,再添加。就像你new RadioButton(...)
後再add一樣。