繁体   English   中英

单击时更改 FloatingActiongButton 背景和图像颜色

[英]Change FloatingActiongButton background and image color when clicked

我想在 Android 中进行此布局,单击按钮时我想更改背景颜色。

目前在 XML 我有app:backgroundTint="@color/white" ,但是当我单击按钮时,我希望背景颜色变为蓝色,并且检查符号颜色变为白色。

您可以使用选择器而不是单色,可能基于选中的 state,然后在单击按钮时设置选中的 state。


您的选择器可能如下所示:

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

    <item android:color="hex_color" />
</selector>

您需要三个 xml 才能使用自定义复选框。

  1. button_background.xml:用于根据按钮检查 state 更改背景
  2. tick_button_checked.xml:选中 state 按钮可绘制
  3. tick_button_unchecked.xml:未选中 state 按钮可绘制

tick_button_unchecked.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="oval">
            <solid android:color="#ffffff" />
            <size
                android:width="48dp"
                android:height="48dp" />
        </shape>
    </item>

    <item android:drawable="@drawable/ic_check_grey" />

</layer-list>

tick_button_checked.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="oval">
            <solid android:color="#3f43b4" />
            <size
                android:width="48dp"
                android:height="48dp" />
        </shape>
    </item>

    <item android:drawable="@drawable/ic_check_white" />

</layer-list>

button_background.xml

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

activity_main.xml 中的复选框按钮

    <CheckBox
        android:id="@+id/checkbox"
        android:layout_width="48dp"
        android:layout_height="48dp"
        android:background="@drawable/button_background"
        android:button="@android:color/transparent"
        android:checked="false" />

暂无
暂无

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

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