Question

I am trying to get a TextView with white background and rounded corners and text in the middle.

Something that looks like this:

enter image description here

So far I have this but it is not giving me the above effect.

        <TextView
            android:textColor="#000000"
            android:background="#FFFFFF"
            android:text="0" />
Was it helpful?

Solution

First of all, I would create a custom drawable resource for easy implementation of rounded corners.

(place this in res/drawable)

my_bg.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <solid
        android:color="ffffff" />

    <corners
        android:radius="15dp"/>

    <stroke
        android:width="1dp"
        android:color="@android:color/black" />

</shape>

More info on xml drawable resources can be found right here if you want to get into more advanced drawables (gradients, layer-list, animation, etc...)

Then change your TextView in xml layout file to match this:

<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="8dp"
        android:textColor="#000000"
        <!--refer to your custom drawable from earlier-->
        android:background="@drawable/my_bg"
        <!--center text within TextView-->
        android:gravity="center"
        android:text="0" />

I hope this helps, Happy Coding!

OTHER TIPS

Set the gravity

android:gravity="center"

http://developer.android.com/reference/android/widget/TextView.html#attr_android:gravity

You are missing the width and height attribute for TextView.

For the rounded corners use a Shape Drawable

http://developer.android.com/guide/topics/resources/drawable-resource.html#Shape

Under res/drawable

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle"
    >
   <solid android:color="#FFFFFF"/> 
    <corners android:radius="7dp" />
    <stroke android:width="5px"  />
</shape>

Then

<TextView
  android:layout_width="100dp"
  android:layout_height="50dp"
  android:background="@drawable/background"
  android:gravity="center"
  android:text="0"
  android:textColor="#000000" />

Snap

enter image description here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top