简体   繁体   中英

Change FloatingActiongButton background and image color when clicked

I want to make this layout in Android, when the buttons are clicked I want to change the background color.

Currently in the XML I have app:backgroundTint="@color/white" , but when I click the button I want the background color to change to blue and the check symbol color to change to white.

You can use a selector instead of a single colour, maybe based on the checked state and then set the checked state when the button is clicked.


Your selector might look something like this:

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

You need three xml for using custom check box.

  1. button_background.xml: for changing background according to check state of button
  2. tick_button_checked.xml: checked state button drawable
  3. tick_button_unchecked.xml: unchecked state button drawable

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>

CheckBox button in 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" />

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