使用drawable和<shape>在<item> XML中

4

是否可以在 drawable 中使用 XML 资源和 <shape> 属性?

因此,我有这个按钮。

        <Button
            android:layout_marginRight="5dp"
            android:id="@+id/send_button"
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:background="@drawable/send_button" />

这里有一个名为send_button.xml的背景文件:

<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/ic_send_white_48dp" android:state_focused="true"/>
    <item android:drawable="@drawable/ic_send_white_48dp" android:state_pressed="true"/>
    <item android:drawable="@drawable/ic_send_black_48dp"/>

</selector>

目前这个工作得很好。但我还想在可绘制对象后面添加背景颜色和圆角,就像这样:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <corners android:radius="4dp" />

    <gradient
        android:angle="270"
        android:endColor="#88b823"
        android:startColor="#b0dc54" />

</shape>

那么是否可以将这两个XML资源合并起来呢? 到目前为止我尝试的只是显示了drawable,但没有显示shape:
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/ic_send_white_48dp" android:state_focused="true"/>
    <item android:drawable="@drawable/ic_send_white_48dp" android:state_pressed="true"/>
    <item android:drawable="@drawable/ic_send_black_48dp">
        <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
            <corners android:radius="4dp" />

            <gradient android:angle="270" 
                android:endColor="#88b823" 
                android:startColor="#b0dc54" />
        </shape>
    </item>

</selector>

1
尝试将位图和形状组合成图层可绘制对象,然后将其用作背景。 - CommonsWare
1
谢谢,看起来很好用。你能把这个作为答案发一下吗,这样我就可以接受了。我有一个包含两个<item>属性的<layer-list>,第一个是<shape>,第二个是<bitmap>。 - Chris
其实,为什么不回答自己的问题,这样你就可以提供更多你使用的代码。这对于将来看到这个问题的人会更有用。 - CommonsWare
1个回答

5

感谢@CommonsWare指导我找到正确的方向。这是可以工作的代码(目前仅适用于默认状态):

<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/ic_send_white_48dp" android:state_focused="true"/>
    <item android:drawable="@drawable/ic_send_white_48dp" android:state_pressed="true"/>
    <item>
        <layer-list xmlns:android="http://schemas.android.com/apk/res/android">
            <item>
                <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
                    <corners android:radius="4dp" />
                    <solid android:color="@color/action_bar" />
                </shape>
            </item>
            <item>
                <bitmap android:src="@drawable/ic_send_black_48dp" />
            </item>
        </layer-list>
    </item>

</selector>

在我的端上可以工作。谢谢! - Guren

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