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!