Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

detect clipping in android TextView

Tags:

android

I have a TextView in my android application that has a set width on it. It's currently got a gravity of "center_horitonzal" and a set textSize (9sp). I pull values to put on this label from a sqlite database, and some of the values are too large to fit in the TextView at the current textSize.

Is there a way to detect that the text inside a TextView is going to be clipped? I'd like to detect this, and lower the font until it fits. There is a nice property in the iPhone UILabel that handles this called "adjustToFit" (which also has a minimum font size), and I'm basically trying to emulate that.

Here's an example of the TextView that I'm working with:

<TextView android:id="@+id/label5" android:layout_width="62px"
            android:layout_height="wrap_content" android:layout_x="257px"
            android:layout_y="169px" android:textSize="9sp" 
            android:textColor="#000"
            android:typeface="sans" android:textStyle="bold"
            android:gravity="center_horizontal" android:lines="1" />
like image 768
Brian Yarger Avatar asked Oct 14 '09 01:10

Brian Yarger


1 Answers

I found a way to measure the width of text using the TextView's Paint object, and lower it until it fit in the size I needed. Here's some sample code:

    float size = label.getPaint().measureText(item.getTitle());
    while (size > 62) {
        float newSize = label.getTextSize() - 0.5f;
        label.setTextSize(newSize);
        size = label.getPaint().measureText(item.getTitle());
    }
like image 102
Brian Yarger Avatar answered Sep 16 '22 11:09

Brian Yarger