Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I know how many characters can fit into TextView of X dp width?

Is there a way to know how many characters of font size 10sp can fit into a TextView of a fixed width (let's say 100dp)?

I need to track if the whole string will fit (be visible) into a TextView of predefined width.

I haven't been able to find a way to track or calculate this.

like image 709
sandalone Avatar asked Jul 05 '12 14:07

sandalone


1 Answers

Since Android uses proportional fonts, each character occupies a different width. Also if you take kerning into account the width of a string may be shorter than the sum of the widths of individual characters.

So it's easiest to measure the whole string by adding one character at a time until (a) the entire string if found to fit within the limit, or (b) the width of the string exceeds the limit.

The following code shows how to find how many characters of size 11px fits into TextView 100px wide. (You can find formulas to convert between px & dp on the Web).

We'll do it by using measureText(String text, int start, int end) in a loop incrementing the value of end until it it no longer fits the TextView's width.

String text = "This is my string";
int textViewWidth = 100;
int numChars;

Paint paint = textView.getPaint();
for (numChars = 1; numChars <= text.length; ++numChars) {
    if (paint.measureText(text, 0, numChars) > textViewWidth) {
        break;
    }
}

Log.d("tag", "Number of characters that fit = " + (numChars - 1));

If performance is poor, you may try using a binary search method instead of a linear loop.

like image 78
Dheeraj Vepakomma Avatar answered Oct 20 '22 00:10

Dheeraj Vepakomma