Android 不支持 MaterialButtonToggleGroup onButtonChecked 数据绑定

Android MaterialButtonToggleGroup onButtonChecked DataBinding Not Supported

我想在 MaterialButtonToggleGroupMaterialButton 上使用 DataBinding,但是 MaterialButtonToggleGroup 似乎没有 onButtonChecked 属性:

<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)))}">

它没有编译,显示: Cannot find a setter for <com.google.android.material.button.MaterialButtonToggleGroup android:onButtonChecked> that accepts parameter type 'lambda'。有什么帮助吗? (app: onButtonChecked 也不起作用)

我遇到了类似的问题并设法解决了这个问题:

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

您当然可以使用不同于布尔值的输入,但思路应该是一样的。

似乎运气不好,我必须手动设置它们 OnButtonCheckedListener():

单选听力:

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

多选试听:

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