【问题标题】:Elevation shadow won't show on device only on preview仅在预览时才会在设备上显示高程阴影
【发布时间】:2019-04-05 17:35:50
【问题描述】:

我正在尝试为我的布局实现投影效果,并决定使用高程选项。

但由于某种原因,我最终在 Android Studio 预览中看到的内容并没有显示在设备上。我将附上 Android Studio 预览和设备的屏幕截图。我会提供我用过的代码。

[

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="#90000000" />
    <corners android:radius="10dp" />
</shape>


<RelativeLayout
    android:outlineProvider="bounds"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:layout_gravity="center"
    android:paddingLeft="40dp"
    android:paddingRight="40dp"
    android:paddingTop="20dp"
    android:paddingBottom="20dp"
    android:clipToPadding="false">

<RelativeLayout
    android:layout_width="300dp"
    android:layout_height="300dp"
    android:background="@drawable/button_shadow"
    android:elevation="30dp"
    />

</RelativeLayout>

【问题讨论】:

  • 您在哪个版本的 Android 上进行测试?前段时间我升级到 Android Pie 时遇到过这个问题,但没有解决。

标签: android android-layout


【解决方案1】:

elevation 属性仅在 Android 5.0+ 上受支持。所以我认为你是在旧设备上运行你的应用程序。

这里有一个解决方案,您可以使用CardView 来替代RelativeLayout

在你的build.gradle()app 中添加依赖

compile 'com.android.support:cardview-v7:26.0.0'

然后像这样在你的xml文件中使用它

<android.support.v7.widget.CardView
  android:id="@+id/media_card_view"
  android:layout_width="300dp"
  android:layout_height="300dp"
  card_view:cardBackgroundColor="@android:color/white"
  card_view:cardElevation="30dp"
  card_view:cardUseCompatPadding="true">
   ...
</android.support.v7.widget.CardView>

或者您可以使用LayerList 制作自己的阴影,创建一个名为shadow.xml 的文件并将其放在您的Drawable 文件夹中

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<!--the shadow comes from here-->
<item
    android:bottom="0dp"
    android:drawable="@android:drawable/dialog_holo_light_frame"
    android:left="0dp"
    android:right="0dp"
    android:top="0dp">

</item>

<item
    android:bottom="0dp"
    android:left="0dp"
    android:right="0dp"
    android:top="0dp">
    <!--whatever you want in the background, here i preferred solid white -->
    <shape android:shape="rectangle">
        <solid android:color="@android:color/white" />

    </shape>
</item>
</layer-list>

然后你像这样将它分配给你的视图

android:background="@drawable/shadow"

【讨论】:

  • 是的,这似乎正是我正在寻找的。但是您是否展示了我应该如何为具有阴影背景的对象添加 8dp 角半径? @胺
  • 您只需将此属性添加到卡片视图card_view:cardCornerRadius="8dp"
  • 只会将角半径添加到只是背景的cardView,而不是我想要角半径的cardView中的实际对象
猜你喜欢
  • 2015-09-26
  • 2014-06-28
  • 1970-01-01
  • 1970-01-01
  • 2016-08-06
  • 2016-10-25
  • 1970-01-01
相关资源
最近更新 更多