Android MaterialButtonToggleGroup onButtonChecked DataBinding Not Supported

1.2k views Asked by At

I want to use DataBinding on the MaterialButtonToggleGroup with MaterialButton, however it seems like there is no onButtonChecked attribute for MaterialButtonToggleGroup:

<com.google.android.material.button.MaterialButtonToggleGroup
    android:id="@+id/majors_toggleGroup"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="8dp"
    android:onButtonChecked="@{(group, buttonId, isChecked) -> viewModel.recordIndex(group.indexOfChild(group.findViewById(buttonId)))}">

It doesn't compile, shows: Cannot find a setter for <com.google.android.material.button.MaterialButtonToggleGroup android:onButtonChecked> that accepts parameter type 'lambda'. Any help? (app: onButtonChecked doesn' work either)

2

There are 2 answers

0
Sam Chen On BEST ANSWER

Seems no luck, I have to manually set OnButtonCheckedListener() on them:

Single Selection Listening:

binding.fruitsToggleGroup.addOnButtonCheckedListener { group, buttonId, isChecked ->
    if (isChecked)        //only listen for check event, ignore uncheck event
        val checkedIndex = group.indexOfChild(findViewById(buttonId))

        viewModel.setFruitIndex(checkedIndex)
     }
}

Multiple Selection Listening:

binding.majorsToggleGroup.addOnButtonCheckedListener { group, _, _ ->
    val checkedIndexes = mutableListOf<Int>()        //recording each uncheck/check event

    group.checkedButtonIds.forEach {
        val index = group.indexOfChild(findViewById(it))

        checkedIndexes.add(index)
    }

    viewModel.setMajorIndexes(checkedIndexes)
}
1
Goopher On

I had a similar issue and managed to fix it like this:

@BindingAdapter("checkedBtnAttrChanged")
@JvmStatic
fun setToggleGroupChangedListener(toggleGroup: MaterialButtonToggleGroup, listener: InverseBindingListener) {
    toggleGroup.addOnButtonCheckedListener { group, checkedId, isChecked -> listener.onChange() }
}


@BindingAdapter("checkedBtn")
@JvmStatic
fun setChecked(toggleGroup: MaterialButtonToggleGroup, salaryIsPartTime: Boolean?) {
    if (salaryIsPartTime == true) {
        toggleGroup.check(R.id.toggle_is_parttime)
    } else {
        toggleGroup.check(R.id.toggle_is_fulltime)
    }
}

@InverseBindingAdapter(attribute = "checkedBtn")
@JvmStatic
fun getChecked(toggleGroup: MaterialButtonToggleGroup): Boolean {
    when (toggleGroup.checkedButtonId) {
        R.id.toggle_is_fulltime -> return false
        R.id.toggle_is_parttime -> return true
    }

    return false
}

You can of course use a different input than a boolean, but the idea should be the same.