2015-09-02 41 views
1

我試圖將radiobutton動態添加到radiogroup中,但我無法將單選按鈕添加到它。 (它在radiogroup裏面沒有顯示單選按鈕) 該代碼顯示沒有錯誤。Android - 將RadioButton動態添加到RadioGroup

自從今天上午以來,我一直在尋找解決方案。 非常感謝您的幫助!

private void createCustomDialog(){ 
     LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); 

     final Dialog dialog = new Dialog(this); 
     dialog.setTitle("Choose Device"); 
     dialog.setContentView(R.layout.dialog_choose_device); 

     LinearLayout parent = (LinearLayout)dialog.findViewById(R.id.linearLayoutCD); 

     LinearLayout li = new LinearLayout(this); 
     li.setLayoutParams(params); 
     li.setOrientation(LinearLayout.VERTICAL); 



     RadioGroup rg = (RadioGroup)dialog.findViewById(R.id.rgCD); 
     RadioButton[] rbArray = new RadioButton[bdList.size()]; 

     for(int i = 0; i < bdList.size(); i++){ 
      rbArray[i] = new RadioButton(this); 
      rbArray[i].setHeight(ViewGroup.LayoutParams.WRAP_CONTENT); 
      rbArray[i].setWidth(ViewGroup.LayoutParams.MATCH_PARENT); 
      rbArray[i].setText(bdList.get(i).getName()); 
      rbArray[i].setId(i); 
      Log.d(LOG, "" + bdList.get(i).getName()); 
      li.addView(rbArray[i]); 

     } 

     Button btnOK = new Button(this); 


     btnOK.setOnClickListener(new View.OnClickListener(){ 
      public void onClick(View view){ 

       dialog.dismiss(); 
      } 
     }); 

    ((ViewGroup) dialog.findViewById(R.id.rgCD)).addView(li); 

    dialog.show(); 
} 

我的XML文件對話框

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="match_parent" android:layout_height="match_parent" 
android:id="@+id/linearLayoutCD" 
android:orientation="vertical"> 
<RadioGroup 
    android:id="@+id/rgCD" 
    android:layout_height="wrap_content" 
    android:layout_width="match_parent" 
    android:orientation="vertical"> 


</RadioGroup> 

<Button 
    android:id="@+id/btnOK" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:text="OK" 
    /> 


</LinearLayout> 

回答

1

試試這個:

RadioGroup rg = (RadioGroup) findViewById(R.id.RadioGroup); 

RadioButton radioButton = new RadioButton(this); 
radioButton.setText("radio text"); 
radioButton.setId(1234);//set radiobutton id and store it somewhere 
RadioGroup.LayoutParams params = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.WRAP_CONTENT, RadioGroup.LayoutParams.WRAP_CONTENT); 
rg.addView(radioButton, params); 
+0

它的作品!非常感謝:D –

相關問題