single material Toggle button with image

538 views Asked by At

I am using Google Material design library in my app and quite surprised that the it does not have the Toggle button. There is toggle button group but what do I do if I need a single button to toggle on and off. My usecase is show one image when on and another when off. I tried to do it with switches but have to a lot of complex customization. Is there any way I can use a simple Material Button as togglebutton?

1

There are 1 answers

0
Gabriele Mariotti On BEST ANSWER

You can use something like:

<com.google.android.material.button.MaterialButton
    android:id="@+id/toogleButtton"
    style="@style/ToggleButton"
    android:checkable="true"
    android:layout_width="48dp"
    android:layout_height="48dp"
    app:icon="@drawable/ic_add_24px"/>

and

   toogleButtton.setIcon(createHeaderToggleDrawable(this))
   toogleButtton.isChecked = true

    // Create StateListDrawable programmatically
    private fun createHeaderToggleDrawable(context: Context): Drawable {
        val toggleDrawable = StateListDrawable()
        toggleDrawable.addState(
            intArrayOf(android.R.attr.state_checked),
            AppCompatResources.getDrawable(context, R.drawable.xxx)
        )
        toggleDrawable.addState(
            intArrayOf(),
            AppCompatResources.getDrawable(context, R.drawable.xxxx)
        )
        return toggleDrawable
    }

Customize your color in the style:

<style name="ToggleButton" parent="Widget.MaterialComponents.Button.TextButton">
    <item name="iconTint">?attr/colorPrimary</item>
    <item name="android:insetTop">0dp</item>
    <item name="android:insetBottom">0dp</item>
    <item name="android:padding">12dp</item>
    <item name="rippleColor">@color/mtrl_btn_ripple_color</item>
</style>

enter image description here