简体   繁体   中英

Change background on FloatingActionButton?

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

在此输入图像描述

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?

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!

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.

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.

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

in xml

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

in code

mFlaotsetBackgroundTintList(ColorStateList.valueOf(Color.Blue))

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