Android TextView Background-ThrowExceptions

Exception or error:

i have a design which demands a background like the image below for the number on the right hand side. Is there any we can achieve this in Android ?

enter image description here

Will i need to make a 9 patch image and set it as a background ?

How to solve:

First, create a shape to have rounded corners.

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#FFFFFF"/>
    <corners android:radius="5px"/>
    <padding android:left="0dp" android:top="0dp" android:right="0dp" android:bottom="0dp" /> 
</shape>

Then apply this as the background to your Views:

<LinearLayout
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/rounded_edges">
    <TextView 
        android:id="@+id/mytext"
        android:layout_width="200dip"
        android:layout_height="wrap_content"
        android:text="blah blah blah blah"
        android:padding="6dip"
        android:textColor="#000000" />
</LinearLayout>

You may need to do some tweaking. You may even be able to discard the LinearLayout and set the android:background of the TextView to @drawable/rounded_edges

###

First create a drawable resource.

<?xml version="1.0" encoding="utf-8"?>
<!--  res/drawable/rounded_textview.xml -->
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" android:padding="10dp">
 <solid android:color="#cccccc"/>
    <corners
     android:bottomRightRadius="15dp"
     android:bottomLeftRadius="15dp"
  android:topLeftRadius="15dp"
  android:topRightRadius="15dp"/>
</shape>

Then reference this drawable in your layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:padding="5dip"
    android:gravity="center"
    android:background="@drawable/rounded_textview" />
</LinearLayout>

One of the good Reference :

TextView with rounded corners

Thanks.

###

I know this is an old question but for anyone who struggles with this, I strongly recommend ViewBadger library

Leave a Reply

Your email address will not be published. Required fields are marked *