-1
rd1 = (RadioButton) findViewById(R.id.rd1); 
rd2 = (RadioButton) findViewById(R.id.rd2); 
rd3 = (RadioButton) findViewById(R.id.rd3); 
rd4 = (RadioButton) findViewById(R.id.rd4); 

RadioGroup rg = new RadioGroup(this); 
rg.addView(rd1); 
rg.addView(rd2); 
rg.addView(rd3); 
rg.addView(rd4); 
rd1.setChecked(true); 

的錯誤是:你必須要求孩子的父母removeview()首先.... 有人幫我...錯誤添加單選按鈕,無線電集團 - Removeview()

+0

如果在你的佈局中定義了RadioButton,爲什麼不把它們放在RadioGroup裏呢?那就是,你爲什麼要在代碼中這樣做? –

+0

因爲每個單選按鈕位於不同的表格行中。這是一個測驗。你可以幫我解決方案.. –

+0

看看這裏的想法:http://stackoverflow.com/questions/10461005/how-to-group-radiobutton-from-different-linearlayouts –

回答

2

問題您的視圖是以XML創建的(這就是爲什麼您必須使用findViewById)

這意味着它們已經連接到您定義它們的XML樹中的父節點。

你有兩個選擇:

正確的方法是在XML來定義RadioGroup中,無論是用收音機裏面,或者再編程方式創建並添加無線電

或壞的(快,但哈克)的方式是:

rd1 = (RadioButton) findViewById(R.id.rd1); 
... 

((ViewGroup) rd1.getParent()).removeView(rd1); 
... 

RadioGroup rg = new RadioGroup(this); 
rg.addView(rd1); 
... 
rd1.setChecked(true); 
+0

問題是我的單選按鈕是在不同的TableRow。我有什麼解決方案? :( –