RadioGroup上的getCheckedRadioButtonId()使用数据绑定android没有给出正确的值

时间:2016-04-21 08:24:29

标签: java android android-layout android-studio

我正在尝试在无线电组上使用验证。但我可以看到如果没有选中单选按钮,则getCheckedRadioButtonId()的返回值不为-1。我正在使用数据绑定。

广播组的xml文件。

<RadioGroup
    android:id="@+id/LabRadioGroup"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:checkedButton="@+id/sound">

    <RadioButton
        android:id="@+id/radio_normal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:checked="@{Exams.result.equals(@string/Exam_Normal)?true:false}"
        android:text="Normal" />

    <RadioButton
        android:id="@+id/radio_abnormal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:checked="@{Exams.result.equals(@string/Exam_Abnormal)?true:false}"
        android:text="Abnormal" />

    <RadioButton
        android:id="@+id/radio_unknown"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:checked="@{Exams.result.equals(@string/Exam_unknown)?true:false}"
        android:text="Unknown" />

</RadioGroup>

enter image description here

这是屏幕截图中的调试值。

Java代码

private boolean Validation() {
    int radiogroup = binding.LabRadioGroup.getCheckedRadioButtonId();
    if (binding.LabRadioGroup.getCheckedRadioButtonId() == -1) {
        binding.radioNormal.setError(CommonMessages.GROUP_RADIO_ERROR_TAG);
        return false;
    }
    return true;
}

1 个答案:

答案 0 :(得分:1)

您正在checkedButton中分配xml属性:

<RadioGroup
android:id="@+id/LabRadioGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checkedButton="@+id/sound">  //<--- remove this line

即使没有选中任何内容,您也会收到此id