Search code examples
androidandroid-listviewtextviewandroid-adapternine-patch

Resizing TextView to fit text (with a nine patch background image)?


I am using a TextView and a 9 patch image as its background for a messaging application in android.

Here's what it looks like: enter image description here

See how for the blue, it is showing too much on the left? How can I reduce it when it decides that it has to wrap the text?

I tried to access the Width and Height fields on the view in public View getView(int position, View convertView, ViewGroup parent), however they are always zero (ps the TextView is located inside of a ListView and the getView method is inside the adapter for the ListView).

Thank you!


TextView XML:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<TextView
    android:id="@+id/message_text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="5sp"
    android:background="@drawable/bubble_b"
    android:shadowColor="@color/textShadow"
    android:shadowDx="1"
    android:shadowDy="1"
    android:text="Medium Text"
    android:textColor="#000000"
    android:textSize="16sp"
    android:lineSpacingMultiplier="1.1" />
</LinearLayout>

Also, here's a screen of what the nine-patch does for it, so you can see how that works for it:

enter image description here


Solution

  • In the iPad picture you attached, iMessage is setting maxWidth to the half of the screen I guess.

    So you can get Screen Width and set maxWidth to half of it for your TextView This is how you can get screen width and pass it to your TextView,

    Display display = ((WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
    yourTextView.setMaxWidth(display.getWidth()/2);
    

    P.S. getWidth method for Display class says deprecated, you can find alternative solution to this. You can get width of your LinearLayout also.

    This is how it looks on my device