如何在Android支持设计库提供的FAB中添加阴影?

问题描述 投票:53回答:6

标题很自我解释。

以下代码不会在浮动操作按钮下方渲染阴影。渲染阴影可以做些什么?即使在API 21+上也不支持此功能吗?

<android.support.design.widget.FloatingActionButton
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:src="@drawable/ic_add"
    android:clickable="true" />

注意:添加android:elevation不会在API 21上添加阴影。

屏幕截图取自dandar3:https://github.com/dandar3/android-support-design

android floating-action-button android-design-library appcompat-v7-r22.2
6个回答
92
投票

简单地设置app:borderWidth="0dp"解决了这个问题。

注意:不要忘记将xmlns:app="http://schemas.android.com/apk/res-auto"添加到根布局。

这个issue应该在Android设计库的下一个版本中修复。


32
投票

对于API 21+,您需要设置app:borderWidth="0dp"app:elevation="[number]dp"。设置高程,您可以获得所需的阴影大小:

以下是API 21+的代码示例:

<android.support.design.widget.FloatingActionButton
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/locate_user_FAB"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/location_off"
    app:elevation="6dp"
    app:borderWidth="0dp"
    android:layout_above="@+id/take_taxi_FAB"
    app:backgroundTint="@color/colorAccentGrey">

对于低于21(Android 4)的API,要记住的一个重要事项是兼容性条款FAB会在按钮周围设置边距以绘制阴影。然后你应该做那样的事情(我目前正在使用这个代码并且工作):

<android.support.design.widget.FloatingActionButton
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/locate_user_FAB"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/location_off"
    app:elevation="6dp"
    app:borderWidth="0dp"
    android:layout_above="@+id/take_taxi_FAB"
    android:layout_alignParentRight="true"
    android:layout_marginRight="@dimen/map_FAB_marginRight"
    android:layout_marginBottom="@dimen/locate_user_FAB_marginBottom"
    app:backgroundTint="@color/colorAccentGrey">

我更喜欢将xmlns:app="http://schemas.android.com/apk/res-auto"放在XML的开头,但我只是为了提醒你;


5
投票

如果这对某些人仍然不起作用,则之间存在显着差异:

app:elevation="6dp"
app:borderWidth="0dp"

app:borderWidth="0dp"
app:elevation="6dp"

由于某种原因,订单似乎很重要(第一个订单有效,第二个订单没有),这来自支持库23.3.0


5
投票

检查Application标签中的项目或库中的清单并删除它们

android:hardwareAccelerated="false"
android:largeHeap="true"

但是如果你需要这些选项,那么阴影和转换动画将无效


5
投票

我遇到了同样的问题,我通过从AndroidManifest.xml中删除此标记来实现它。

android:hardwareAccelerated="false"

我最初和android:largeHeap="true"一起添加它,因为我认为我需要它来展示一个热点地图,其中显示了大量的点,但后来我意识到它可以与android:largeHeap="true"一起使用。


0
投票

如果它有帮助,我正在使用

android:tint="@color/myColor"

代替

android:backgroundTint="@color/myColor".

用backgroundTint替换色调带回了阴影。

© www.soinside.com 2019 - 2024. All rights reserved.