仅在预览中看到高程阴影而在设备上无法显示

5
我正在尝试为我的布局添加阴影效果,决定采用高程选项。但是在Android Studio预览中看到的效果在设备上却无法显示。我将附上Android Studio预览和设备的截图,并提供我使用的代码。

[1] enter image description here

<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时遇到了这个问题,但没有解决。 - Haroun Hajem
1个回答

3

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圆角添加到具有阴影背景的对象中?@Amine - Peter
你只需要将这个属性添加到卡片视图中 card_view:cardCornerRadius="8dp" - Amine
这只会将圆角添加到卡片视图的背景,而不是我想要圆角的实际对象内部的卡片视图。 - Peter
请查看此问题:https://stackoverflow.com/questions/55558861/how-to-get-corner-radius-on-layer-list-shadow-background - Peter

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