Option 1: Shape Drawable
This is the simplest option if you want a border around a layout or view in which you can set the background. Create an XML file in the drawable
folder that looks something like this:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<solid android:color="#8fff93" />
<stroke
android:width="1px"
android:color="#000" />
</shape>
You can remove the solid
if you don't want a fill. The set background="@drawable/your_shape_drawable"
on your layout/view.
Option 2: Background View
Here's a little trick I've used in a RelativeLayout
. Basically you have a black square under the view you want to give a border, and then give that view some padding (not margin!) so the black square shows through at the edges.
Obviously this only works properly if the view doesn't have any transparent areas. If it does I would recommend you write a custom BorderView
which only draws the border - it should only be a few dozen lines of code.
<View
android:id="@+id/border"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/image"
android:layout_alignLeft="@+id/image"
android:layout_alignRight="@+id/image"
android:layout_alignTop="@+id/main_image"
android:background="#000" />
<ImageView
android:id="@+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_...
android:padding="1px"
android:src="@drawable/..." />
If you're wondering, it does work with adjustViewBounds=true
. However, it doesn't work if you want to have a background in an entire RelativeLayout
, because there is a bug that stops you filling a RelativeLayout
with a View
. In that case I'd recommend the Shape
drawable.
Option 3: 9-patch
A final option is to use a 9-patch drawable like this one:
You can use it on any view where you can set android:background="@drawable/..."
. And yes it does need to be 6x6 - I tried 5x5 and it didn't work.
The disadvantage of this method is you can't change the colours very easily, but if you want fancy borders (e.g. only a border at the top and bottom, as in this question) then you may not be able to do them with the Shape
drawable, which isn't very powerful.
Option 4: Extra views
I forgot to mention this really simple option if you only want borders above and below your view. You can put your view in a vertical LinearLayout
(if it isn't already) and then add empty View
s above and below it like this:
<View android:background="#000" android:layout_width="match_parent" android:layout_height="1px"/>