Logo Icon Logo
A Crowd-sourced Cookbook on Writing Great Android® Apps
GitHub logo Twitter logo OReilly Book Cover Art
Adding a Border with Rounded Corners to a LayoutBack to Android Cookbook Home | Up to Chapter: Graphical User Interface

Author: Daniel Fowler ('GR8DAN')
In Published Edition? Yes
FormatLanguage: WikiFormat

Adding a Border with Rounded Corners to a Layout


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">
    <corners android:radius="20dp"/>
    <padding android:left="10dp" android:right="10dp" android:top="10dp" android:bottom="10dp"/>
    <solid android:color="#CCCCCC"/>

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 [1] for detailed information on a shape file.

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"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      <LinearLayout android:orientation="vertical"
      <TextView android:layout_width="fill_parent"
                android:text="Text View"
                android:background="#A00000FF" />

Which produces:

See Also