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

时间:2015-11-02 14:16:34

标签: android

是否可以使用具有drawable和<shape>属性的XML-Background资源?

所以我有这个按钮

        <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资源组合起来吗? 到目前为止我尝试过的只是显示可绘制的而不是形状:

<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 个答案:

答案 0 :(得分:1)

感谢@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>