how to put a border around an android relativelayout?

AyaAndro picture AyaAndro · May 3, 2012 · Viewed 33.6k times · Source

I've seen this subject about puting a border around an android textview, and I used it. But now, I would like to put a border around widgets which are situated into a relative layout. How can I do it?

Answer

RWIL picture RWIL · Oct 19, 2015
  1. in your res/drawable folder, create a new file background_border.xml

In this file, you will define the background for widget like this:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle" >
    <!-- This is the stroke you want to define -->
    <stroke android:width="1dp" 
            android:color="@color/color_stroke"/>

    <!-- Optional, round your corners -->
    <corners android:bottomLeftRadius="0dp"
             android:topLeftRadius="5dp"
             android:bottomRightRadius="5dp"
             android:topRightRadius="0dp" />

    <!-- Optional, fill the rest of your background with a color or gradient, use transparent if you only want the border to be displayed-->
    <gradient android:startColor="@android:color/transparent"
              android:endColor="@android:color/transparent"
              android:angle="90"/>
</shape>
  1. set the background of your widget to the drawable configuration you've just created

eg. if you want to put your border on a relativelayout:

<RelativeLayout            
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@drawable/background_border"
            android:padding="15dp">
    ...
</RelativeLayout>