简体   繁体   English

如何创建带有图标和文本的切换按钮

[英]How to create toggle button with icon and text

What would be the best way to build a togglebutton in android like shown in the image below.在 android 中构建切换按钮的最佳方法是什么,如下图所示。 I spend more time than i like to admit trying to get it right but so far it seems inpossible to get rounded background and an icon at the same time.我花的时间比我想承认的要多,但到目前为止似乎不可能同时获得圆形背景和图标。

My Layout我的布局

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

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>

BG BG

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

按钮示例

What i got我得到了什么

在此处输入图像描述

You can use a MaterialButton with android:checkable="true" :您可以将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"
        ../>

where btn_toggle_background is a selector其中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>

with:和:

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

在此处输入图像描述

在此处输入图像描述

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

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