单击时更改浮动操作按钮背景和图像颜色



我想做这个布局在Android中,当点击按钮时,我想更改背景颜色。

目前在XML中我有CCD_ 1,但当我点击按钮时,我希望背景颜色变为蓝色,复选符号颜色变为白色。

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


您的选择器可能看起来像这样:

<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:用于根据按钮的检查状态更改背景
  2. tick_button_checked.xml:可绘制的检查状态按钮
  3. tick_button_nchecked.xml:未选中状态按钮可绘制

tick_button_nnchecked.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" />