防止RelativeLayout环绕背景图片

时间:2018-06-26 01:28:40

标签: android android-relativelayout

我有一个RelativeLayout。我想对其施加阴影效果,所以我定义了一个自定义背景( updatebg.xml ):

    <layer-list xmlns:android="http://schemas.android.com/apk/res/android">

        <item android:id="@+id/background" >
            <shape android:shape="rectangle">
                <solid android:color="#449966"/>
            </shape>
        </item>

        <item android:id="@+id/shadow">
            <bitmap  android:src="@drawable/shadow" 
                android:layout_width="wrap_content"  
                android:layout_height="wrap_content"  
            />
        </item>
    </layer-list>

和RelativeLayout:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:id="@+id/layoutP"
    android:background="@drawable/updatebg"
    >
</RelativeLayout>

除RelativeLayout拉伸到与背景图像高度(阴影)相同的高度外,其他所有方法都效果很好。如果我的RelativeLayout内部内容的高度小于阴影背景图像的高度,那么RelativeLayout也将被拉伸为“环绕背景”,而不仅仅是环绕RelativeLayout内部的内容。

我需要将背景图像调整为父母的身高(RelativeLayout)或被裁剪掉。关于如何完成此操作的任何提示?谢谢!

我正在尝试从上到下应用阴影的渐变类型: enter image description here

1 个答案:

答案 0 :(得分:3)

修改

也许我误会了您所说的“阴影效果”,如果您只想渐变,请使用<gradient> drawable。

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:id="@+id/background" >
        <shape android:shape="rectangle">
            <solid android:color="#449966"/>
        </shape>
    </item>
    <item>
        <shape
            android:dither="true"
            android:shape="rectangle" >
            <gradient
                android:angle="270"
                android:endColor="#7fffffff"
                android:startColor="#7f000000" />
        </shape>
    </item>
</layer-list>

结果类似于:

result

原始答案

您应该考虑改用9-Patch png。就像这样:

9-Patch

这只是普通的png图像,但带有一些附加标记(边框上的黑点/线条),Android会根据需要使用这些标记来拉伸图像。

有关如何使用9-Patch文件的详细信息,请参见the official docs