2011-07-11 40 views
25

我想要創建一系列與Android應用程序中的字符串數組對應的單選按鈕。單選按鈕應該切換要從數組中顯示的內容。我該怎麼做呢?以編程方式創建單選按鈕

+0

到目前爲止你做了些什麼。告訴我們你的進度,所以我們可以幫你 –

回答

58

您必須添加單選按鈕到RadioGroup,然後RadioGrouplayout

我錯過喜歡的是提交的,但你的代碼看起來應該像一些信息:

private void createRadioButton() { 
    final RadioButton[] rb = new RadioButton[5]; 
    RadioGroup rg = new RadioGroup(this); //create the RadioGroup 
    rg.setOrientation(RadioGroup.HORIZONTAL);//or RadioGroup.VERTICAL 
    for(int i=0; i<5; i++){ 
     rb[i] = new RadioButton(this); 
     rg.addView(rb[i]); //the RadioButtons are added to the radioGroup instead of the layout 
     rb[i].setText("Test"); 
    } 
    ll.addView(rg);//you add the whole RadioGroup to the layout 
    ll.addView(submit); 
    submit.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View v) { 
      for(int i = 0; i < 5; i++) { 
       rg.removeView(rb[i]);//now the RadioButtons are in the RadioGroup 
      } 
      ll.removeView(submit); 
      Questions(); 
     } 
    }); 
} 

其他驗證碼動態創建radiobutton

<TableRow> 
    <RadioGroup 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:orientation="vertical" 
     android:id="@+id/radiobuttons"> 
    </RadioGroup> 
</TableRow> 

代碼:

public void makeRadioButtons(Vector tmpVector, int i, LinearLayout.LayoutParams lp) 
{ 
    RadioButton rb = new RadioButton(this); 
    rb.setText((String) tmpVector.elementAt(i)); 
    //rg is private member of class which refers to the radio group which I find 
    //by id. 
    rg.addView(rb, 0, lp); 

} 
+0

** ll.removeView(submit); **? – partho

+0

@partho我想它代表一個'LinearLayout'實例? – stkent

相關問題