首页 > 解决方案 > 单一材质 带图像的切换按钮

问题描述

我在我的应用程序中使用 Google Material 设计库,并且很惊讶它没有切换按钮。有切换按钮组,但如果我需要一个按钮来打开和关闭,我该怎么办。我的用例是打开时显示一张图像,关闭时显示另一张图像。我试图用开关来做,但必须进行很多复杂的定制。有什么方法可以使用简单的材质按钮作为切换按钮?

标签: androidmaterial-designandroid-buttonmaterial-components-android

解决方案


你可以使用类似的东西:

<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"/>

   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
    }

自定义样式中的颜色:

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

在此处输入图像描述


推荐阅读