[英]RadioGroup.clearCheck() not working in case of dynamically created radio buttons
[英]how to set dynamically created Radio buttons into a 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中?
謝謝!
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);
}
這清楚地表明,如果我們嵌套收音機,那么它將無法工作。 所以我想,你必須以其他方式去手動。
在List<RadioButton>
添加您的RadioButtons
,然后您可以使用它來檢查它們
mRadioList.get(i).setChecked(true);
你可以像Ovidiu建議的那樣將它們添加到List中,但由於它們不在RadioGroup中,除了設置在位置i檢查了RadioButton之外,你應該將setChecked(false)設置為所有其他RadioButton。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.