简体   繁体   中英

Floating Action Button background color does not change on disabling when custom background color is set

In my App I want to disable a FAB in certain cases. But when the FAB has a custom backgroundTint, the background color of that FAB stays the same(does not change to the disabled FAB background color). The FAB is disabled but the color does not change.

Here is an Example: the layout file

<com.google.android.material.floatingactionbutton.FloatingActionButton
                android:id="@+id/deleteButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/ic_baseline_clear_24"
                app:tint="@color/white"
                app:backgroundTint="@color/darkgray_02"
                android:layout_margin="10dp"/>

And here is the Code:

binding.deleteButton.isEnabled = false

Here an Image with the corresponding code

A: isEnabled = false, no custom color

B: isEnabled = false, app:backgroundTint="@color/darkgray_02"

在此处输入图像描述

Is there a way to set a custom color for the FAB and to disable the FAB at the same time, so that the color changes to the default FAB disabled color when I disable the FAB?

Ok so I figured it out. There are other posts about it it turns out.

To have multiple states of the FAB(enabled and disabled) you need to set a ColorStateList instead of a single color. So I created an xml: drawable/fab_custom_style.xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:alpha="0.12" android:color="?attr/colorOnSurface" android:state_enabled="false"/>
    <item android:color="@color/darkgray_02"/>
</selector>

and set the backgroundTint to use this xml's selector:

app:backgroundTint="@drawable/fab_custom_style.xml"

Now the FAB has two states for disabled and enabled.

For disabled FAB I use the FAB's standard disabled color = "?attr/colorOnSurface" (Found it here: https://github.com/material-components/material-components-android/blob/master/lib/java/com/google/android/material/floatingactionbutton/res/color/mtrl_fab_bg_color_selector.xml )

For the enabled FAB I use my custom color: "@color/darkgray_02"

Sorry for being late. I use to change a FAB background color in this way:

  1. We know that a FAB background is a drawable.

  2. instead of creating a drawable just to change the background color you could do this

    yourFabButton.getBackground().setTint(getContext().getColor(R.color.colorPrimary));

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