Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Scale TextView background image to Fit XY

I have the following textview which uses a simple navbar png file as its background image. Here's the code:

<TextView
        android:id="@+id/titleNameText"
        android:layout_width="wrap_content"
        android:layout_height="50dp"
        android:background="@drawable/navbar"
        android:gravity="center_horizontal"
        android:singleLine="true"
        android:textColor="@color/WHITE"
        android:textSize="18sp"
        android:textStyle="bold" />

The problem is that on bigger screens the navbar doesn't scale horizontally to fit the screen, how do I solve this?

like image 741
Dave Avatar asked Feb 20 '13 11:02

Dave


2 Answers

Put an imageview behind the TextView and make it's size correspond to the size of the TextView using android:align...:

<RelativeLayout android:layout_width="wrap_content"
                android:layout_height="wrap_content">
    <ImageView android:layout_width="match_parent"
               android:layout_height="match_parent"
               android:layout_alignBottom="@id/titleNameText"
               android:layout_alignLeft="@id/titleNameText"
               android:layout_alignRight="@id/titleNameText"
               android:layout_alignTop="@id/titleNameText"
               android:scaleType="fitXY"
               android:src="@drawable/navbar"/>

    <TextView
        android:id="@+id/titleNameText"
        android:layout_width="wrap_content"
        android:layout_height="50dp"
        android:background="@drawable/navbar"
        android:gravity="center_horizontal"
        android:singleLine="true"
        android:textColor="@color/WHITE"
        android:textSize="18sp"
        android:textStyle="bold"/>
</RelativeLayout>
like image 126
Hans Avatar answered Nov 16 '22 13:11

Hans


The android:background set to a TextView (in this context) doesn't have the attribute android:scaleType="fitXY" (or any other value for that matter). That attribute is found on ImageViews and ImageButtons.

That being said, I would make 2 suggestions for your current situation.

  1. Change the android:layout_width="wrap_content" to android:layout_width="fill_parent". Naturally the drawable set to the TextView will respect the width of the TextView. I am merely speculating (no screenshot in the OP) that the content isn't wide enough on larger display to fill the width.

  2. If you aren't doing so already, use either a Shape Drawable XML or a 9-patch. This will ensure consistent quality across multiple screen sizes.

If I am completely wrong, post a screen shot. That will make things clearer. ;-)

like image 24
Siddharth Lele Avatar answered Nov 16 '22 12:11

Siddharth Lele