2011-11-04 26 views
0

我的XML文件添加RadioButton的動態

<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); 



} 
當我運行這段代碼獲得異常

「這個規定的孩子已經有一個父」。請告訴我的朋友是什麼在我的代碼問題,並請給我任何建議。

回答

2

只是不添加RG線性佈局,這是RadioGroup中在XML文件中

+0

@ekjyot ...非常感謝..... – sarath

+0

U r WElcome @sarath – ekjyot

0

的LinearLayout中已經存在試試這個代碼,希望這將有助於

RadioGroup rg=(RadioGroup)findViewById(R.id.rgc); 
     RadioButton rb; 

     for(int i=0;i<4;i++) 
     { 
      rb=new RadioButton(this); 
      rb.setText(i+"aaaaaa"); 
      rg.addView(rb,i,new ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT)); 

     } 

     rg.invalidate(); 
+0

...好的建議..... – sarath