Search code examples
androidandroid-drawableandroid-styleslayer-list

Style bottom Line in Android


I need to create an android shape so that only the bottom has stroke (a dashed line). When I try the following, the stroke bisects the shape right through the center. Does anyone know how to get it right? the stroke needs to be the bottom line/border. I am using the shape as a background to a TextView. Please, never mind why I need it.

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

    <item>
        <shape android:shape="rectangle" >
            <solid android:color="#1bd4f6" />
        </shape>
    </item>

    <item>
        <shape android:shape="line" >
            <padding android:bottom="1dp" />

            <stroke
                android:dashGap="10px"
                android:dashWidth="10px"
                android:width="1dp"
                android:color="#ababb2" />
        </shape>
    </item>

</layer-list>

Solution

  • It's kind of a hack, but I think this is probably the best way to do it. The dashed line will always be on the bottom, regardless of the height.

    <layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    
        <item>
            <shape android:shape="rectangle" >
                <solid android:color="#1bd4f6" />
            </shape>
        </item>
    
        <item android:top="-2dp" android:right="-2dp" android:left="-2dp">
            <shape>
                <solid android:color="@android:color/transparent" />
                <stroke
                    android:dashGap="10px"
                    android:dashWidth="10px"
                    android:width="1dp"
                    android:color="#ababb2" />
            </shape>
        </item>
    
    </layer-list>
    

    Explanation:

    The second shape is transparent rectangle with a dashed outline. The key in making the border only appear along the bottom lies in the negative margins set the other sides. These negative margins "push" the dashed line outside the drawn area on those sides, leaving only the line along the bottom. One potential side-effect (which I haven't tried) is that, for views that draw outside their own bounds, the negative-margin borders may become visible.