You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Android Studio中用XML制作布局背景自定义Drawable并实现图中效果

实现目标布局背景的XML方案

根据你提供的效果参考图,以下是两种通过XML实现该背景的方案:

方案一:使用layer-list自定义Drawable

创建res/drawable/top_round_background.xml文件,实现顶部圆角+阴影的背景效果:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- 阴影层 -->
    <item>
        <shape android:shape="rectangle">
            <solid android:color="#1A000000" />
            <corners android:topLeftRadius="16dp" android:topRightRadius="16dp" />
            <padding android:bottom="2dp" />
        </shape>
    </item>
    <!-- 主背景层 -->
    <item android:bottom="2dp">
        <shape android:shape="rectangle">
            <solid android:color="#FFFFFF" />
            <corners android:topLeftRadius="16dp" android:topRightRadius="16dp" />
        </shape>
    </item>
</layer-list>

在布局中引用该Drawable:

<View
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/top_round_background" />

如果需要渐变背景,将主背景层的<solid>替换为渐变代码:

<gradient
    android:startColor="#F8F8F8"
    android:endColor="#ECECEC"
    android:angle="90" />

方案二:使用CardView快速实现

如果你的项目依赖AndroidX,直接用CardView可以更简单地实现带圆角和阴影的背景:

<androidx.cardview.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:cardCornerRadius="16dp"
    app:cardElevation="4dp"
    app:cardPreventCornerOverlap="false"
    app:cardUseCompatPadding="true">
    <!-- 内部布局内容 -->
</androidx.cardview.widget.CardView>

内容的提问来源于stack exchange,提问作者Muhammad Hamza

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 20:10:32