androidmaterial-designandroid-databindingandroid-jetpackandroid-binding-adapter

Android MaterialButtonToggleGroup onButtonChecked DataBinding Not Supported


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)


Solution

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