以下是我目前的解决方案:
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:onCheckedChanged="@{(group, buttonId) -> student.setGenderIndex(group.indexOfChild(group.findViewById(buttonId)))}"
android:orientation="horizontal">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:checked="@{student.genderIndex == 0}"
android:text="Male" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="@{student.genderIndex == 1}"
android:text="Female" />
</RadioGroup>
这工作正常,但我想知道是否有更好的方法来做到这一点。RadioGroup
然后我发现:(android:checkedButton
来自官方文档)有一个内置的双向属性,但它id
不是我想要的索引:
public static final int checkedButton
The id of the child radio button that should be checked by default within this radio group.
May be an integer value, such as "100".
Constant Value: 16843080 (0x01010148)
我仍然尝试(使我的绑定表达式更短)但不起作用:
android:onCheckedChanged="@{(group, buttonId) -> student.setGenderIndex(group.indexOfChild(group.checkedButton))}"
说"Could not find accessor android.widget.RadioGroup.checkedButton"