简体   繁体   中英

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

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

   <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

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

在此处输入图像描述

在此处输入图像描述

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