How to add padding to gradient <shape> in Android?

I have a shape with a gradient that I'm using as a divider between ListView items. I've defined it as follows:

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

<gradient
    android:startColor="#ccd0d3"
    android:centerColor="#b6babd"
    android:endColor="#ccd0d3"
    android:height="1px"
    android:angle="0" />

</shape>

I would like to add 6 pixels of padding on either side of the gradient, so that it doesn't extend from edge to edge of the screen.

However, no matter where I put an android:left="6px" and android:right="6px", it doesn't seem to take effect. I can put it in the <shape> element, the <gradient> element, or in a separate <padding> child of <shape>, and it doesn't change anything.

How can I add padding on the left and right of my list divider?


Solution 1:

I guess you could combine it like this:

<?xml version="1.0" encoding="UTF-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:left="6dp"
          android:right="6dp">

        <shape android:shape="rectangle">
            <gradient android:startColor="#ccd0d3"
                      android:centerColor="#b6babd"
                      android:endColor="#ccd0d3"
                      android:height="1px"
                      android:angle="0"/>
        </shape>
    </item>
</layer-list>

Solution 2:

Another solution using inset:

<?xml version="1.0" encoding="UTF-8"?>
<inset xmlns:android="http://schemas.android.com/apk/res/android"
    android:insetLeft="6dp"
    android:insetRight="6dp" >

    <shape   
        android:shape="rectangle">

    <gradient
        android:startColor="#ccd0d3"
        android:centerColor="#b6babd"
        android:endColor="#ccd0d3"
        android:height="1px"
        android:angle="0" />

    </shape>

</inset>

Solution 3:

One solution seems to be to "wrap" my drawable with another drawable that specifies the appropriate padding.

For example, list_divider.xml would be:

<?xml version="1.0" encoding="UTF-8"?>
<layer-list
    xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:left="6dp"
        android:right="6dp"
        android:drawable="@drawable/list_divider_inner" />

</layer-list>

And then list_divider_inner.xml would be the original drawable:

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

<gradient
    android:startColor="#ccd0d3"
    android:centerColor="#b6babd"
    android:endColor="#ccd0d3"
    android:height="1px"
    android:angle="0" />

</shape>

This results in two files to specify a simple divider though. I don't know if there's a way to do it with only one file though.