Chris
Chris

Reputation: 4372

Use drawable and <shape> in <item> XML

Is it possible to use a XML-Background ressource with an drawable and a <shape> attribute?

So I have this button

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

Which has a background 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>

This works fine right now. But I also want to add a background-color behind the drawable and rounded corners like this:

<?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>

So is it possible to combine these two XML ressources? What I've tried so far, just displays the drawable and not the 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>

Upvotes: 4

Views: 10023

Answers (1)

Chris
Chris

Reputation: 4372

Thanks to @CommonsWare for pointing me in the right direction. This is the working code (currently only for the default state):

<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>

Upvotes: 5

Related Questions