如何更改FAB背景颜色

30
我正在使用浮动操作按钮,并希望更改背景颜色。 这是我的代码。
    <android.support.design.widget.FloatingActionButton
        android:id="@+id/btnfab"
        android:layout_width="48dp"
        android:layout_height="48dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_gravity="right|center_vertical"
        android:layout_marginBottom="20dp"
        android:src="@drawable/search" />

这是我正在使用的代码来尝试实现此目标:

1- android:background="@color/mycolor"
2- android:backgroundTint="@color/white"

我也在我的FAB上出现了像图片中显示的那样的角落。我应该如何消除这些角落的阴影?

在此输入图片描述


请在 build.gradle 中添加依赖项。 - piotrek1543
我没有添加任何fab依赖项。我只是通过创建BlankActivity,然后将其复制粘贴到我的项目中来使用fab。它使用我的项目的主题颜色。 - Ritesh
请查看有关FAB“角落”的帖子:https://dev59.com/3ZLea4cB1Zd3GeqPyinc#34345100 - Konstantin Loginov
@Ritesh 我已经更新了我的答案。 - Damian Kozlak
4个回答

49
您可以通过将以下属性添加到您的FloatingActionButton来去除问题阴影:
app:borderWidth="0dp"
app:elevation="6dp"

FloatingActionButton 没有背景颜色。您可以通过以下方式更改此组件的颜色:

app:backgroundTint="@color/YOURCOLOR"

请确保在您的父布局中包含以下行:

xmlns:app="http://schemas.android.com/apk/res-auto"

9

在您的应用程序样式中声明以下内容:

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

干杯


1
您IP地址为143.198.54.68,由于运营成本限制,当前对于免费用户的使用频率限制为每个IP每72小时10次对话,如需解除限制,请点击左下角设置图标按钮(手机用户先点击左上角菜单按钮)。 - tir38
虽然这可能不是每个人的好解决方案(如果他们想要与FAB不同的colorAccent),但在我的情况下,这是完美的解决方案。 - Soren Stoutner

7

首先在styles.xml中创建一个样式:

<style name="PrimaryActionButton" parent="Theme.AppCompat.Light">
<item name="colorAccent">@color/colorPrimary</item>
</style>

然后将您的浮动操作按钮(FAB)的主题设置为此样式:

<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_favorite_white_24dp"
android:theme="@style/PrimaryActionButton"
app:fabSize="normal"
app:rippleColor="@color/colorAccent" />

你可以在此链接中查看完整描述:Android:悬浮操作按钮

2
这样你就可以支持低于21的API。而被接受的答案则没有这样做。 - ahmadkarimi12
我同意... 对于API小于21的情况,这是解决方案。这也适用于更新的API,因此这是最通用的答案。 - Smitty-Werben-Jager-Manjenson
这是最佳解决方案。 - Basil Battikhi

6
请在build.gradle中更新您的Android支持库和Android Material Design库。
(请将您的build.gradle文件添加到上面)
根据这些网站: 以及Android Developers参考文献,您应该仅使用:
   android:backgroundTint="@color/white"

据我记得,对于浮动操作按钮来说,这个阴影是一个众所周知的问题,因此请看一下这些额外的库:

http://android-arsenal.com/tag/173

这可能会帮助您更换此损坏的元素。

还要检查:

希望能对您有所帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接