Since Android uses proportional fonts , each character has a different width. Also, if you accept kerning , the line width may be shorter than the sum of the width of the individual characters.
Thus, it is easiest to measure the entire line by adding one character at a time until (a) the entire line, if it falls within the limit, or (b) the line width exceeds the limit.
The following code shows how many 11px characters fit into a TextView 100px wide. (You can find formulas for converting between px and dp on the Internet).
We will do this using measureText(String text, int start, int end)
in a loop, increasing the value of end
until it no longer matches the width of the TextView
.
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 can try using the binary search method instead of a linear loop.
source share