我可以在一个Android drawable中使用多个形状吗?

21
我想要做的是为LinearLayout定义一个通用的背景,该背景在应用程序的许多Activity中频繁使用。这个特定的布局是一个标题,显示在每个活动的顶部。
我想创建一个drawable,使其填充LinearLayout并具有渐变色,并在渐变下方显示一条水平线。是否有人知道是否可能实现这一点,或者我必须只能使用嵌套布局来完成这种事情。
我的尝试是 drawable xml:
 <selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <gradient android:startColor="#AA000000" android:endColor="#AA333333"
        android:angle="270" />
</shape>
</item>
<item>
<shape android:shape="line">
    <stroke android:width="3dp" android:color="#FFFFFFFF"
            android:dashWidth="1dp" android:dashGap="2dp" />
    <size android:height="5dp" />
</shape>
</item>
</selector>
2个回答

41

Drawable接受多个形状(总是在其他文件中定义),如果我理解你的问题,也许你可以做一个Layer drawable(这将在彼此之上绘制多个基础drawable)。

我在这里写下这个,所以我没有测试过,但是尝试使用并阅读这个很棒的文档。

<?xml version="1.0" encoding="utf-8"?>
    <layer-list xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:drawable="@drawable/shape_7"/>
        <item android:drawable="@drawable/shape_1"/>
    </layer-list>

Android完整的XML资源

干杯


28
可以将它们垂直排列吗?也就是在Y坐标轴上。 - android developer
1
将android命名空间添加到每个项目中:<item xmlns:android="http://schemas.android.com/apk/res/android" ... />,这样就完美了。 - Philiiiiiipp
1
很好的观点@Philiiiiiipp。然而,在图层列表中添加命名空间就足够了,而不是在列表中的每个项目中添加它。像这样:<layer-list xmlns:android="http://schemas.android.com/apk/res/android">。 - MemoryLeak
有没有人能提供一种解决方案,使形状可以在Y坐标轴上一个接一个地创建? - Akash Bisariya

5

使用gravity属性在layer-list中设置你的items

    对于竖直方向,请使用:
    android:gravity="top"
    android:gravity="center"
    android:gravity="bottom"
    对于水平方向,请使用:
    android:gravity="left"
    android:gravity="center"
    android:gravity="right"
<layer-list
           xmlns:android="http://schemas.android.com/apk/res/android">
          <item>
                <bitmap
                   android:src="@drawable/top_img"
                   android:gravity="top"/>
          </item>
          <item>
                <bitmap
                   android:src="@drawable/center_img"
                   android:gravity="center"/>
          </item>
          <item>
                <bitmap
                   android:src="@drawable/bottom_img"
                   android:gravity="bottom"/>
          </item>
</layer-list>

确保父元素有足够的空间容纳所有项目!否则它们会重叠在一起。


我使用两个答案结合 @Franco - Noor Hossain

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