2011-09-02 78 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。

相关问题