简体   繁体   中英

single material Toggle button with image

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?

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>

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM