tags:

views:

3809

answers:

2

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?

+12  A: 

There is no built-in "border" concept in Android that I can think of. You can emulate one through layouts, such as:

  • Wrap the TextView in a LinearLayout and add a plain View above and below it, with the Views having the desired android:background color and an appropriate android:layout_height (e.g., 1px, 1dip).
  • Wrap the TextView in a LinearLayout and add ImageView widgets above and below with your desired border images.
  • Wrap the TextView in a RelativeLayout, add in a plain View (with proper background & height) anchored to the top, another plain View anchored to the bottom, and your TextView anchored to the top and bottom. This takes advantage of RelativeLayout's z-axis support, so the border will be inside the space taken up by the TextView, rather than being outside the TextView as in the first two approaches.
  • Give the TextView a nine-patch PNG file as a background that has your borders. This is simplest from the XML standpoint, but you have to craft an appropriate nine-patch image.
CommonsWare
Thanks commonsware. That's a good answer. I've used 9-patches and linear/relative layouts in the past, but was hoping that the platform might have a simpler and more performant solution.
Mike
+1  A: 

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.

okaram