3

I am trying to set the background of a FAB to a different color in XML. I know I could do this in code, but that would also require a lot of inconvenient refactoring on my part.

<android.support.design.widget.FloatingActionButton
    android:layout_width="40dp"
    android:layout_height="40dp"
    android:background="#F38E1B"
    android:id="@+id/fab"/>

enter image description here

For some reason, the background stays blue when it should be orange. I have tried setting the background to a drawable as well but that yields the same results.

Is this a bug or am I just missing something?

Kevin Cronly
  • 1,388
  • 1
  • 13
  • 18
  • 1
    You can try it : setBackgroundColor(int color) from the official documentation https://developer.android.com/reference/android/support/design/widget/FloatingActionButton.html – FlavienBert Jun 16 '15 at 16:57
  • @FlavienBert I did, and I got the same result. And as I said, doing this through code would require a lot of refactoring. – Kevin Cronly Jun 16 '15 at 17:16

5 Answers5

4

I also tried to use the same approach as you and was getting the same result. My solution was to was to this:

<item name="colorAccent">@color/yourColor</item>

in my application theme.

However, this color will also be used in all your widgets.

Hope this helps!

harry perry
  • 123
  • 1
  • 8
3

I had the same problem. This is how I solve my issue: I just create a new theme to my button.

My FAB xml:

<android.support.design.widget.FloatingActionButton
      ...
      android:theme="@style/MapButton"/>

My new theme in style.xml:

<style name="MapButton" parent="AppTheme">
        <item name="colorAccent">#FFFFFF</item></style>

I created a new theme based on my App's theme and changed only the color I wanted.

Hope it helps.

Pedro Acácio
  • 139
  • 1
  • 5
2

Ok I figured it out. Turns out you do have to set the background to a drawable (thanks @Nilesh), but there was something wrong with the drawable I was setting it to. I used this:

<?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="@color/al_color_accent_orange_light"/>
        </shape>
    </item>
</layer-list>

as my drawable and it worked.

Kevin Cronly
  • 1,388
  • 1
  • 13
  • 18
1

As FloatingActionButton extends ImageView

see this link

Also see the line no 76

they are getting background as drawable and you are setting the color

so I don't think you can change it using color.

try setting drawable as background

see this link and line no 20

N J
  • 27,217
  • 13
  • 76
  • 96
1

in xml

<android.support.design.widget.FloatingActionButton
    ...
    app:backgroundTint="@color/background_tint"
    android:src="@drawable/ic_add" />

in code

mFlaotsetBackgroundTintList(ColorStateList.valueOf(Color.Blue))
dinus
  • 141
  • 1
  • 2