I have a TextView and I'd like to add a black border along its top and bottom borders. I tried adding android:drawableTop
and android:drawableBottom
to the TextView, but that only caused the entire view to become black.
<TextView
android:background="@android:color/green"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:drawableTop="@android:color/black"
android:drawableBottom="@android:color/black"
android:text="la la la" />
Is there a way to easily add a top and bottom border to a View (in particular, a TextView) in Android?
You can also use a 9-path to do your job. Create it so that colored pixel do not multiply in height but only the transparent pixel.
I've used a trick so that the border is displayed outside the container. With this trick only a line is drawn so the background will be shown of the underlying view.
Why not just create a 1dp high view with a background color? Then it can be easily placed where you want.
In android 2.2 you could do the following.
Create an xml drawable such as /res/drawable/textlines.xml and assign this as a TextView's background property.
/res/drawable/textlines.xml
The down side to this is that you have to specify an opaque background colour, as transparencies won't work. (At least i thought they did but i was mistaken). In the above example you can see that the solid colour of the first shape #FFffffdffffd is copied in the 2nd shapes stroke colour.
To add a
1dp
white border at the bottom only and to have a transparent background you can use the following which is simpler than most answers here.For the
TextView
or other view add:And in the
drawable
directory add the following XML, calledborderbottom.xml
If you want a border at the top, change the
android:top="-2dp"
toandroid:bottom="-2dp"
The colour does not need to be white and the background does not need to be transparent either.
The
solid
element may not be required. This will depend on your design (thanks V. Kalyuzhnyu).Basically, this XML will create a border using the rectangle shape, but then pushes the top, right and left sides beyond the render area for the shape. This leaves just the bottom border visible.
You can also wrap the view in a FrameLayout, then set the frame's background color and padding to what you want; however, the textview, by default has a 'transparent' background, so you'd need to change the textview's background color too.