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?
To add a border to Android TextView we need to create an XML containing shape as a rectangle file under the drawable's folder and set it as background to the TextView. <stroke> tag is used to set the border width and color.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml. In the above code we have taken one text view with background as border so we need to create a file in drawable as boarder.
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.
<TextView android:text="My text with lines above and below" android:background="@drawable/textlines" />
/res/drawable/textlines.xml
<?xml version="1.0" encoding="utf-8"?> <layer-list xmlns:android="http://schemas.android.com/apk/res/android" > <item> <shape android:shape="rectangle"> <stroke android:width="1dp" android:color="#FF000000" /> <solid android:color="#FFDDDDDD" /> </shape> </item> <item android:top="1dp" android:bottom="1dp"> <shape android:shape="rectangle"> <stroke android:width="1dp" android:color="#FFDDDDDD" /> <solid android:color="#00000000" /> </shape> </item> </layer-list>
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 #FFdddddd is copied in the 2nd shapes stroke colour.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With