【问题标题】:How to create toggle button with icon and text如何创建带有图标和文本的切换按钮
【发布时间】:2023-03-02 22:07:01
【问题描述】:

如下图所示,在 android 中构建切换按钮的最佳方法是什么。我花费的时间比我想承认的要多,但到目前为止似乎不可能同时获得圆形背景和图标。

我的布局

            <ToggleButton
            android:id="@+id/addButton"
            android:layout_width="match_parent"
            android:layout_height="45dp"
            android:background="@drawable/button_bg_rounded_corners"
            android:button="@drawable/check"

检查

    <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/app_checkmark"
        android:state_checked="true" />
    <item android:drawable="@drawable/app_close"
        android:state_checked="false"/>
    </selector>

背景

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true">

        <shape android:shape="rectangle" >
            <solid android:color="@color/appcolor_yellow" />
            <corners android:radius="20dp" />
        </shape>
    </item>
    <item android:state_checked="false" >
        <shape android:shape="rectangle" >
            <solid android:color="@color/appcolor_green"/>
            <corners android:radius="20dp" />
        </shape>
    </item>
</selector>

我得到了什么

【问题讨论】:

  • 我建议您使用com.google.android.material.button.MaterialButton。它具有app:iconapp:iconGravityapp:iconSizeapp:iconTintapp:backgroundTint 等属性。有了这些,您就可以实现图片上描述的 UI。是的,它实际上不是ToggleButton,但对我来说,在ViewModelFragment 中本地跟踪toggled 状态比尝试为背景创建适当的xml 更容易。

标签: android android-layout android-button material-components-android


【解决方案1】:

您可以将MaterialButtonandroid:checkable="true" 一起使用:

   <com.google.android.material.button.MaterialButton
        android:checkable="true"
        app:backgroundTint="@drawable/btn_toggle_background"
        app:iconGravity="start"
        app:icon="@drawable/..."
        app:cornerRadius="20dp"
        ../>

btn_toggle_background 是一个选择器

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="false" android:color="@color/..." />
    <item android:state_checked="true" android:color="@color/..." />
</selector>

与:

    button.addOnCheckedChangeListener { button, isChecked ->
        if (isChecked){
            button.icon = ContextCompat.getDrawable(this,R.drawable.xxx)
        } else {
            button.icon = ContextCompat.getDrawable(this,R.drawable.xxx)
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-02
    • 1970-01-01
    • 2013-09-07
    • 1970-01-01
    • 2019-05-26
    • 2015-04-23
    • 2016-09-03
    相关资源
    最近更新 更多