androidmaterial-designandroid-buttonandroid-togglebuttonmaterialbutton

How to get checked button position in Android MaterialButtonToggleGroup


I have defined an MaterialButtonToggleGroup with 2 MaterialButton in my xml, in this way:

<com.google.android.material.button.MaterialButtonToggleGroup
    ...
    app:checkedButton="@+id/favorite_color1"
    app:singleSelection="true">

    <com.google.android.material.button.MaterialButton
        android:id="@+id/favorite_color1"
        ... />

    <com.google.android.material.button.MaterialButton
        android:id="@+id/favorite_color2"
        ... />

</com.google.android.material.button.MaterialButtonToggleGroup>

I found getCheckedButtonIds() method (that returns a List of Ids) and OnButtonCheckedListener (that returns an Integer Id), but the get(int index) method returns the View at the index position, not the View with a certain id.

How Can I get (programmatically) the View of the checked button in a given moment? There is a method returns the current checked position (or index)?


Solution

  • Since you are using app:singleSelection="true" you can use thegetCheckedButtonId() method to get the unique id of the selected MaterialButton in this group.
    You can use something like:

    MaterialButtonToggleGroup materialButtonToggleGroup = 
             findViewById(R.id.toggle_button_group);
    int buttonId = materialButtonToggleGroup.getCheckedButtonId();
    MaterialButton button = materialButtonToggleGroup.findViewById(buttonId);
    

    You can also use getCheckedButtonIds() and cycle over the ids.

    List<Integer> ids = materialButtonToggleGroup.getCheckedButtonIds();
    for (Integer id:ids){
          MaterialButton materialButton = materialButtonToggleGroup.findViewById(id);
          //....
    }