2

Following is my current solution:

<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>

This works fine, but I'm wondering if there is a better way to do this. And then I find out that there is a built-in two-way attribute for RadioGroup: android:checkedButton (from Official Documentation), however it is the id not the index I want:

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)

I still try (to make my binding expression shorter) but doesn't work:

android:onCheckedChanged="@{(group, buttonId) -> student.setGenderIndex(group.indexOfChild(group.checkedButton))}"

Says "Could not find accessor android.widget.RadioGroup.checkedButton"

Sam Chen
  • 7,597
  • 2
  • 40
  • 73

1 Answers1

1

Add onCheckedChanged like this

<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>

Then in your view model implement onSplitTypeChanged like this

fun onSplitTypeChanged(radioGroup: RadioGroup?, id: Int) {
        val checked = radioGroup?.findViewById<RadioButton>(id)
        val index = radioGroup?.indexOfChild(checked)
    }
mohsen
  • 1,065
  • 16
  • 24