Can I find out how many characters can fit in a TextView of width x dp?

Is there a way to find out how many characters in a 10sp font size can fit in a fixed width TextView (say 100dp)?

I need to keep track of whether the entire string will match (be visible) in a TextView with a predefined width.

I was unable to find a way to track or calculate this.

+6
source share
2 answers

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.

+6
source

The best way to determine this is to simply test it. Since you are using DP, it will be relatively device independent. If you do not use a font with a fixed width, there really is no way to determine it theoretically, unless you really want to try to measure the width of each letter, kerning, etc. And compare with the width of the TextView

0
source

Source: https://habr.com/ru/post/919770/


All Articles