同时检查单选按钮

时间:2013-01-15 20:01:45

标签: android radio-button radio-group

我正在运行时使用以下代码创建一个带有单选按钮(来自枚举)的无线电组。

RadioGroup radioGroup = new RadioGroup(this);

List<LocationTypeEnum> warningTypes = preferences.getWarningTypes();
for (LocationTypeEnum enumElement : warningTypes) {
    RadioButton radio = new RadioButton(this);
    radio.setText(enumElement.toString());

    //Check one specific radio by default
        radio.setChecked(enumElement.intValue == userDefinedLocation.getType().intValue);

    radioGroup.addView(radio, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
}

当涉及到屏幕并且我尝试更改收音机时,两个选项仍保持检查:

enter image description here

出了什么问题?

2 个答案:

答案 0 :(得分:3)

找到答案。您必须将RadioButton添加到RadioGroup 之前将其设置为选中,否则无线电组将丢失。以下是正确的代码。

    RadioGroup radioGroup = new RadioGroup(this);

    List<LocationTypeEnum> warningTypes = preferences.getWarningTypes();
    for (LocationTypeEnum enumElement : warningTypes) {
        RadioButton radio = new RadioButton(this);
        radio.setText(enumElement.toString());

        //First, add the radio to the group
        radioGroup.addView(radio, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));

        //Only after that you can check it.
        radio.setChecked(enumElement.intValue == userDefinedLocation.getType().intValue);

    } 

听起来像个臭虫,对我来说。致http://code.google.com/p/android/issues/detail?id=1772

的积分

答案 1 :(得分:0)

不知道如何评论要求您发布布局.xml文件。确保您还将它们分组到xml文件中,如下所示:

<RadioGroup
        android:id="@+id/radioSex"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

        <RadioButton
            android:id="@+id/radioMale"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/radio_male" 
            android:checked="true" />

        <RadioButton
            android:id="@+id/radioFemale"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/radio_female" />

    </RadioGroup>