2012-11-26 40 views
2

當我在一個XML佈局創建一個文件RadioGroup中一切的優良正確選擇/取消,但是當我動態創建它的另一個選擇當單選按鈕不取消:單選按鈕不要在動態創建RadioGroup中

enter image description here

下面的代碼:

public class MainActivity extends Activity { 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radioGroup1); 

    RadioButton radioButtonView = new RadioButton(this); 
    radioButtonView.setText("RadioButton"); 
    radioGroup.addView(radioButtonView); 

    RadioButton radioButtonView2 = new RadioButton(this); 
    radioButtonView2.setText("RadioButton2"); 
    radioGroup.addView(radioButtonView2); 
} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.activity_main, menu); 
    return true; 
} 
} 

而且佈局文件:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
tools:context=".MainActivity" > 

<RadioGroup 
    android:id="@+id/radioGroup1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignParentTop="true" > 
</RadioGroup> 
</RelativeLayout> 

回答

5

您需要設置某種ID爲您的單選按鈕,因爲這樣的:

int idRadio = <some number>; 
radioButtonView.setId(idRadio++); 
radioButtonView2.setId(idRadio++); 

一旦他們有獨特的ID,它應該工作。只要確保這些ID不與任何現有的圖形元素相沖突,並且不爲零(轉到「gen」文件夾並查看R.java中的其他元素ID)。

+0

就是這樣,謝謝!爲什麼地球上就是這樣設置的? – Jonathan

+0

操作系統跟蹤資產以及屬於它的人員非常有用。另外,當您正在查找用戶選擇的對象時,通常查詢返回的ID比查看所有單選按鈕更容易,並找出哪個對象被選中。另外,如果這是您接受的答案,請點擊答案旁邊的複選標記標記爲答案。 :-) –

+0

有用,當然,但正確的UI功能的先決條件?無論如何,謝謝你的修復。 – Jonathan

相關問題