2011-09-02 119 views
2

我有動態創建的單選按鈕。如何將動態創建的單選按鈕設置爲RadioGroup?

     LinearLayout linLayRoot = (LinearLayout)dialogView.findViewById(R.id.dialog_layout_root); 
     RadioGroup radGp = new RadioGroup(this); 
     linLayRoot.addView(radGp); 

     for (String dir : dirArray) 
     { 

       LinearLayout linLayNew = new LinearLayout(this); 
       linLayNew.setGravity(0x10); 
       RadioButton radBut = new RadioButton(this); /// <- this button does not work! 
       radBut.setText(""); 
       TextView tv = new TextView(this); 
       tv.setText(dir); 
       tv.setPadding(10, 0, 20, 0); 
       ImageView ivs = new ImageView(this); 

       linLayNew.addView(radBut); 
       linLayNew.addView(tv); 
       linLayNew.addView(ivs); 

       radGp.addView(linLayNew); 

     } 

      RadioButton radBut1 = new RadioButton(this); /// <- this button works! 
      radBut1.setId(11); 
      radBut1.setText("a1"); 
      radGp.addView(radBut1); 

      RadioButton radBut2 = new RadioButton(this); /// <- this button works! 
      radBut2.setId(12); 
      radBut2.setText("b2"); 
      radGp.addView(radBut2); 

     radGp.setOnCheckedChangeListener(new OnCheckedChangeListener() 
     { 
      @Override 
      public void onCheckedChanged(RadioGroup group, int checkedId) { 
       Toast.makeText(getApplicationContext(), String.valueOf(checkedId) , Toast.LENGTH_SHORT).show(); 
      } 
     }); 

但你可以從上面的評論看,他們並沒有真正的工作,即好像他們沒有綁定到radGp ......也許它,因爲他們是在一個單獨的linlearlayout?

謝謝!

回答

3

添加您的List<RadioButton>RadioButtons,您可以通過使用

mRadioList.get(i).setChecked(true); 
4

RadioGroup有一個addView這需要一個視圖作爲輸入,檢查它們則。從這裏看來,你可以添加LinearLayout作爲一個孩子。 RadioGroup真的是一個LinearLayout。

UPDATE

我檢查的RadioGroup.java

@Override 
public void addView(View child, int index, ViewGroup.LayoutParams params) { 
    if (child instanceof RadioButton) { 
     final RadioButton button = (RadioButton) child; 
     if (button.isChecked()) { 
      mProtectFromCheckedChange = true; 
      if (mCheckedId != -1) { 
       setCheckedStateForView(mCheckedId, false); 
      } 
      mProtectFromCheckedChange = false; 
      setCheckedId(button.getId()); 
     } 
    } 

    super.addView(child, index, params); 
} 

源這清楚地表明,如果我們窩無線電那麼它將無法工作。 所以我想,你必須去其他方式手動。

+0

查看上面的編輯,工作沒有錯誤,但仍然允許用戶選擇多個按鈕。 :/ – Roger

+0

@Roger:我編輯了我的回覆。畢竟,我們似乎必須去手動。 – Samuel

1

您可以將它們添加到Ovidiu建議的列表中,但由於它們不在RadioGroup中,除了設置在位置i處選中RadioButton,您應該將setChecked(false)設置爲所有其他RadioButton。

相關問題