Android – Borders on layouts with transparent backgrounds
by Riley MacDonald, October 23, 2014

This technique is especially handy for controlling which sides of the layout the border is drawn to.

Create a new drawable resource with a root element of layer-list in the drawable directory of your project. Save this resource with a name which best describes it usage such as “top_border”. Following the code snippet below stroke controls the border while solid controls the background of the desired layout. This example draws a 1dp border on the top of the layout. Define which sides should have a border by using android:left/top/right/bottom in item (as shown below) with an opposite value of the stroke width.

<!-- top_border.xml -->
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:left="-1dp" android:bottom="-1dp" android:right="-1dp">
        <shape android:shape="rectangle">
            <stroke android:width="1dp" android:color="@color/border_color" />
            <solid android:color="@color/background_color" />
        </shape>
    </item>
</layer-list>

Apply the above drawable resource to your layout using android:background attribute (see example below):

<!-- Layout to apply the border to -->
<LinearLayout android:id="@+id/topBorderedLayout"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:background="@drawable/top_border">
</LinearLayout>

The layout now has a border drawn on the top. If the background_color provided to solid is transparent it will remain transparent!

Open the comment form

Leave a comment:

Comments will be reviewed before they are posted.

User Comments:

Jon on 2016-10-11 14:35:07 said:
Thanks very helpful. I always forget how to do this.