#android #data-binding #android-databinding #2-way-object-databinding #android-binding-adapter
#Android #привязка данных #android-привязка данных #2-way-object-databinding #android-привязка-адаптер
Вопрос:
Ниже приведено мое текущее решение:
<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"
Ответ №1:
Добавьте onCheckedChanged
вот так
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onCheckedChanged="@{vm.onSplitTypeChanged}">
<RadioButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/email" />
<RadioButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/sms" />
</RadioGroup>
Затем в вашей модели представления реализуется onSplitTypeChanged
следующим образом
fun onSplitTypeChanged(radioGroup: RadioGroup?, id: Int) {
val checked = radioGroup?.findViewById<RadioButton>(id)
val index = radioGroup?.indexOfChild(checked)
}