简体   繁体   English

单一材质 带图像的切换按钮

[英]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.我在我的应用程序中使用了 Google Material design library,并且很惊讶它没有 Toggle 按钮。 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>

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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