簡體   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