ChatGPT解决这个技术问题 Extra ChatGPT

Android changing Floating Action Button color

I have been trying to change Material's Floating Action Button color, but without success.

<android.support.design.widget.FloatingActionButton
    android:id="@+id/profile_edit_fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="end|bottom"
    android:layout_margin="16dp"
    android:clickable="true"
    android:src="@drawable/ic_mode_edit_white_24dp" />

I have tried to add:

android:background="@color/mycolor"

or via code:

FloatingActionButton fab = (FloatingActionButton) rootView.findViewById(R.id.profile_edit_fab);
fab.setBackgroundColor(Color.parseColor("#mycolor"));

or

fab.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#mycolor")));

But none of the above worked. I have also tried the solutions in the proposed duplicate question, but none of them works; the button remained green and also became a square.

P.S. It would be also nice to know how to add ripple effect, couldn't understand that either.

Ripple effect is not available on pre-lollipop devices because it utilizes a new RenderThread.
@karaokyo ok but how am I doing it?
Google does a real bad job in my opinion to make these things accesible
To do this programmatically and backwards compatible, see stackoverflow.com/questions/30966222/…

M
Marko

As described in the documentation, by default it takes the color set in styles.xml attribute colorAccent.

The background color of this view defaults to the your theme's colorAccent. If you wish to change this at runtime then you can do so via setBackgroundTintList(ColorStateList).

If you wish to change the color

in XML with attribute app:backgroundTint

<android.support.design.widget.FloatingActionButton
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/ic_add"
    app:backgroundTint="@color/orange"
    app:borderWidth="0dp"
    app:elevation="6dp"
    app:fabSize="normal" >

in code with .setBackgroundTintList (answer below by ywwynm)

As @Dantalian mentioned in the comments, if you wish to change the icon color for Design Support Library up to v22 (inclusive), you can use

android:tint="@color/white"     

For Design Support Library since v23 for you can use:

app:tint="@color/white"   

Also with androidX libraries you need to set a 0dp border in your xml layout:

<com.google.android.material.floatingactionbutton.FloatingActionButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/ic_add"
    app:backgroundTint="@color/orange"
    app:borderWidth="0dp"
    app:elevation="6dp"
    app:fabSize="normal" />

This doesn't work in Design Support Library v23 for < API 12 devices. It was working in v22, so they broke something, apparently.
Note that if you want to also change the image color to white for example you can use: android:tint="@android:color/white"
android:tint="@color/white" didnt work for me because it couldn't resolve it for some reason. android:tint="#ffffff" Works for me though
That is because @color/white does not exists in your colors.xml. use @android:color/white or create a color named white or whatever you need
use "app:backgroundTint" not "android:backgroundTint"
C
Community

Vijet Badigannavar's answer is correct but using ColorStateList is usually complicated and he didn't tell us how to do it. Since we often focus on changing View's color in normal and pressed state, I'm going to add more details:

If you want to change FAB's color in normal state, you can just write mFab.setBackgroundTintList(ColorStateList.valueOf(your color in int)); If you want to change FAB's color in pressed state, thanks for Design Support Library 22.2.1, you can just write mFab.setRippleColor(your color in int); By setting this attribute, when you long-pressed the FAB, a ripple with your color will appear at your touch point and reveal into whole surface of FAB. Please notice that it won't change FAB's color in normal state. Below API 21(Lollipop), there is no ripple effect but FAB's color will still change when you're pressing it.

Finally, if you want to implement more complex effect for states, then you should dig deeply into ColorStateList, here is a SO question discussing it: How do I create ColorStateList programmatically?.

UPDATE: Thanks for @Kaitlyn's comment. To remove stroke of FAB using backgroundTint as its color, you can set app:borderWidth="0dp" in your xml.


Thanks for this, I didn't know how to use ColorStateList. However, your code leaves my FAB with a stroke (outline) of the theme accent color. Do you have any idea how I can remove that stroke (or change it's color, rather) and have a FAB in a special color that looks like that special color is the accent color?
@KaitlynHanrahan Please see my update. Thanks for your comment.
That works perfect -- Lollypop and Kitkat look the same, even both have that little shading so the FAB pops against the same color in the background (I have it partially over the Toolbar). Thanks so much! It's simple but I don't know if I ever would have found that on my own.
Is there a way how to set app:borderWidth programatically? Thanks
@Štarke Well, after looking at the source code of FloatingActionButton, I'm afraid that you cannot set it programatically right now since there is no setter for mBorderWidth.
T
Taslim Oseni

As Vasil Valchev noted in a comment it is simpler than it looks, but there is a subtle difference that I wasn't noticing in my XML.

<android.support.design.widget.FloatingActionButton
    android:id="@+id/profile_edit_fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="end|bottom"
    android:layout_margin="16dp"
    android:clickable="true"
    android:src="@drawable/ic_mode_edit_white_24dp"
    app:backgroundTint="@android:color/white"/>

Notice it is:

app:backgroundTint="@android:color/white"

and not

android:backgroundTint="@android:color/white"

This is important because these are two completely different things: android:backgroundTint="" is from Api level 21 and part of the Lollipop Material Design and will be ignored below Lollipop. Also it doesn't change the FAB colour completely because it is not a solid color. You have to use the app: one to make it work.
Thanks, using android:color caused my app to crash, and it was driving me nuts! Thanks for saving my app and what's left of my sanity ;-)
@Kapenaar no problem, was scratching my head for a while as well before noticing ;)
How would this work programatically since on the java side there is no difference like app: and android: in the XML.
@marienke you can set it with a ColorStatesList, post a new question and post the link here so I can answer it ;)
e
ergo

if you try to change color of FAB by using app, there some problem. frame of button have different color, so what you must to do:

app:backgroundTint="@android:color/transparent"

and in code set the color:

actionButton.setBackgroundTintList(ColorStateList.valueOf(getResources().getColor(R.color.white)));

This work for normal colors. If I have given alpha color like #44000000 the frame color issue is reproducible.
getResources.getColor() is deprecated, consider using ContextCompat.getColor(context, your colour); instead. Hope it helps
A
Ashana.Jackol

just use,

app:backgroundTint="@color/colorPrimary"

dont use,

android:backgroundTint="@color/colorPrimary"

hmmmm this cause android studio autocomplete give result use android:backgroundTint , this answer verry good
t
tachyonflux

The FAB is colored based on your colorAccent.

<style name="AppTheme" parent="Base.Theme.AppCompat.Light">
    <item name="colorAccent">@color/accent</item>
</style>

Well, the default color is not green. Where did you set a green color?
I did not. As you see, this xml is the only place I set up the layout of the button...
Maybe you should create a new project with just the FAB and post the code for the entire thing.
Wow... I basically just asked you to do the same thing and you weren't willing to do it. It is quite hypocritical of you to believe that your code was adequate, but that my addition to your code is not adequate. It falls to the asker to create an MCVE. Thanks.
Not anymore, based on Theme Attribute Mapping the Floating Action Button now (I verified myself) is colored to colorSecondary (com.google.android.material:material:1.1.0-alpha02)
a
atoMerz
mFab.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(mContext,R.color.mColor)));

This is the easiest solution, way easier than using a custom drawable.
l
luca992

New theme attribute mapping for Floating Action Button in material 1.1.0

In your app theme:

Set colorSecondary to set a color for background of FAB (maps to backgroundTint)

Set colorOnSecondary to set a color for icon/text and ripple color of FAB (maps to tint and rippleColor)

<style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
    <!-- ...whatever else you declare in your app theme.. -->
    <!-- Set colorSecondary to change background of FAB (backgroundTint) -->
    <item name="colorSecondary">@color/colorSecondary</item>
    <!-- Customize colorSecondary to change icon/text of FAB (maps to tint and rippleColor) -->
    <item name="colorOnSecondary">@android:color/white</item>
</style>

Finally someone who provides simple solutions for FAB background and foreground (icon) colors.
Thanks. That's what I was looking for
R
Robin Davies

Other solutions may work. This is the 10 pound gorilla approach that has the advantage of being broadly applicable in this and similar cases:

Styles.xml:

<style name="AppTheme.FloatingAccentButtonOverlay" >
    <item name="colorAccent">@color/colorFloatingActionBarAccent</item>
</style>

your layout xml:

<android.support.design.widget.FloatingActionButton
       android:theme="AppTheme.FloatingAccentButtonOverlay"
       ...
 </android.support.design.widget.FloatingActionButton>

Hmm, seems like this should work, but I'm getting compiler errors in the layout file String types not allowed (at 'theme' with value 'AppTheme.FloatingAccentButtonOverlay'). Maybe I'm missing a point with the styles.xml....
@ScottBiggs use android:theme="@style/AppTheme.FloatingAccentButtonOverlay" but this solutin does not work for me either way...
What about API 16 which does not have coloarAccent atrribute?
G
Gabriele Mariotti

With the Material Theme and the material components FloatingActionButton by default it takes the color set in styles.xml attribute colorSecondary.

You can use the app:backgroundTint attribute in xml:

<com.google.android.material.floatingactionbutton.FloatingActionButton
       ...
       app:backgroundTint=".."
       app:srcCompat="@drawable/ic_plus_24"/>

You can use fab.setBackgroundTintList();

You can customize your style using the attribute

  <!--<item name="floatingActionButtonStyle">@style/Widget.MaterialComponents.FloatingActionButton</item> -->
  <style name="MyFloatingActionButton" parent="@style/Widget.MaterialComponents.FloatingActionButton">
    <item name="backgroundTint">#00f</item>
    <!-- color used by the icon -->
    <item name="tint">@color/...</item>
  </style>

starting from version 1.1.0 of material components you can use the new materialThemeOverlay attribute to override the default colors only for some components:

  <style name="MyFloatingActionButton" parent="@style/Widget.MaterialComponents.FloatingActionButton">
    <item name="materialThemeOverlay">@style/MyFabOverlay</item>
  </style>

  <style name="MyFabOverlay">
    <item name="colorSecondary">@color/custom2</item>
    <!-- color used by the icon -->
    <item name="colorOnSecondary">@color/...</item>
  </style>

https://i.stack.imgur.com/OqBj9.png


V
Vijet Badigannavar

The document suggests that it takes the @color/accent by default. But we can override it on code by using

fab.setBackgroundTintList(ColorStateList)

Also remember,

The minimum API version to use this library is 15 so you need to update it! if you dont want to do it then you need to define a custom drawable and decorate it!


works, but then I have to target api 21+. if I target api 8 can't call this method.
Just include this design library that has been released by google "com.android.support:design:22.2.0". This can be used on devices that are non-lollipop versions! cheers!!
of course I do, but this is the error on this code: Call requires API level 21 (current min is 8): android.widget.ImageView#setBackgroundTintList
The minimum API version to use this library is 15 so you need to update it! if you dont want to do it then you need to define a custom drawable and decorate it!
Oh thanks! I didn't know, thought it was 21 since this is what the error said. Please post this as an answer and I'll accept it!
A
Agilanbu

Changing Floating action button background color by using below line

app:backgroundTint="@color/blue"

Changing Floating action button icon color

android:tint="@color/white"     

G
Gaurav Kumar Gupta

Thanks to autocomplete. I got lucky after a few hit and trials:

    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    card_view:backgroundTint="@color/whicheverColorYouLike"

-- or -- (both are basically the same thing)

    xmlns:app="http://schemas.android.com/apk/res-auto"
    app:backgroundTint="@color/whicheverColorYouLike"

This worked for me on API Version 17 with design library 23.1.0.


C
Community

I got the same problem and its all snatching my hair. Thanks for this https://stackoverflow.com/a/35697105/5228412

What we can do..

 favourite_fab.setImageDrawable(ContextCompat.getDrawable(getBaseContext(), R.drawable.favourite_selected));

it works fine for me and wish for others who'll reach here.


Whilst this may theoretically answer the question, it would be preferable to include the essential parts of the answer here, and provide the link for reference.
G
Gavine Joyce
 <android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    app:elevation="6dp"
    app:backgroundTint="@color/colorAccent"
    app:pressedTranslationZ="12dp"
    android:layout_margin="@dimen/fab_margin"
    android:src="@drawable/add"/>

Note that you add colors in res/values/color.xml and include the attribute in your fab

   app:backgroundTint="@color/addedColor"

J
Jan Málek

When using Data Binding you can do something like this:

android:backgroundTint="@{item.selected ? @color/selected : @color/unselected}"

I have made a very simple example


T
Tom

If you have a Floating Action Button with no drawable you can change the tint programmatically using:

fab.getBackground().mutate().setTint(ContextCompat.getColor(yourContext, R.color.anyColor));

Thats the solution I was searchin for. I had a simple fab with backgrountTint and couldn't find a way to change it programmatically until I found this.
I use Data Binding, and I got a NullPointerException...
J
Jwala Kumar

for Material design, I just changed the floating action button color like this, Add the below two lines in your Floating action button xml. And done,

 android:backgroundTint="@color/colorPrimaryDark"
 app:borderWidth="0dp"

s
sana sajjad

i did it like this android:background="@color/colorAccent" i just go to folder res then click on folder values and then on colors.xml in colors.xml I just change the color of colorAccent and call it in android:background and its done


N
Nidia F.

The point we are missing is that before you set the color on the button, it's important to work on the value you want for this color. So you can go to values > color. You will find the default ones, but you can also create colors by copping and pasting them, changing the colors and names. Then... when you go to change the color of the floating button (in activity_main), you can choose the one you have created

Exemple - code on values > colors with default colors + 3 more colors I've created:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>

    <color name="corBotaoFoto">#f52411</color>
    <color name="corPar">#8e8f93</color>
    <color name="corImpar">#494848</color>

</resources>

Now my Floating Action Button with the color I've created and named "corPar":

<android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        android:src="@android:drawable/ic_input_add"
        android:tint="#ffffff"
        app:backgroundTint="@color/corPar"/>

It worked for me. Good Luck!


f
fullmoon

in Kotlin:

val gray = getColor(requireContext(), R.color.green)
binding.fabSubmit.backgroundTintList = ColorStateList.valueOf(gray)

i
inspire_coding

My solution, which worked for me with Data Binding

val color = ContextCompat.getColor(context, R.color.colorPrimary)
binding.fab.backgroundTintList = ColorStateList.valueOf(getColor)

P
Progga Ilma

https://i.stack.imgur.com/N7Dto.png

add colors in color.xml file and then add this line of code... floatingActionButton.setBackgroundTintList(ColorStateList.valueOf(getResources().getColor(R.color.fab2_color)));


O
OhhhThatVarun

You can use this code in case you want to change the color programmatically

floating.setBackgroundTintList(getResources().getColorStateList(R.color.vermelho));

p
passionatedevops

use

app:backgroundTint="@color/orange" in


<com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/id_share_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/share"
        app:backgroundTint="@color/orange"
        app:fabSize="mini"
        app:layout_anchorGravity="end|bottom|center" />



</androidx.coordinatorlayout.widget.CoordinatorLayout>


M
Mori

You can use Extended, so set app:iconTint like this:

<com.google.android.material.floatingactionbutton.ExtendedFloatingActionButton
        android:id="@+id/fAB"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
       
        app:icon="@drawable/d0"
        app:iconTint="@color/white"
         />