Adding a Border with Rounded Corners to a Layout
Author: Daniel Fowler
There is a need to put a border around an area of the screen or add interest to a user interface.
Define an Android shape in an XML file and assign it to a layout's background attribute.
The drawable folder, under res, in an Android project is not restricted to bitmaps (PNG or JPG files) but can also hold shapes defined in XML files. These shapes can then be reused in the project. A shape can be used to put a border around a layout. This example shows a rectangular border with curved corners. A new file called customborder.xml is created in the drawable folder. (With the drawable folder selected in Android Studio use the context menu, normally right-click, or the File menu and select New then Drawable resource file. In the New Drawable Resource File dialog enter a File name of customborder. Set the Root element to shape. Click OK.). The XML defining the border shape is entered:
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<padding android:left="10dp" android:right="10dp" android:top="10dp" android:bottom="10dp"/>
The attribute android:shape is set to rectangle (shape files also support oval, line and ring). Rectangle is the default value so this attribute could be left out if it is a rectangle being defined. See the Android documentation on shapes at  for detailed information on a shape file.
- The element corners sets the rectangle corners to be rounded, it is possible to set a different radius on each corner (see the Android reference).
- The padding attributes are used to move the contents of the View to which the shape is applied, to prevent the contents overlapping the border.
- The border color here is set to a light gray (CCCCCC hexadecimal RGB value).
Shapes also support gradients but that is not being used here, again see the Android resources to see how a gradient is defined. The shape is applied to the laypout using android:background="@drawable/customborder". Within the layout other views can be added as normal, in this example a single TextView has been added, the text is white (FFFFFF hexadecimal RGB). The background is set to blue, plus some transparency to reduce the brightness (A00000FF hexadecimal alpha RGB value). Finally the layout is offset from the screen edge by placing it into another layout with a black background and a small amount of padding. The full layout file is thus:
<?xml version="1.0" encoding="utf-8"?>
The source code for this project can be downloaded from http://tekeye.uk/android/examples/download/layoutborder.zip.