How to find android TextView number of characters per line?

Try this:

private boolean isTooLarge (TextView text, String newText) {
    float textWidth = text.getPaint().measureText(newText);
    return (textWidth >= text.getMeasuredWidth ());
}

Detecting how many characters fit will be impossible due to the variable width of the characters. The above function will test if a particular string will fit or not in the TextView. The content of newText should be all the characters in a particular line. If true, then start a new line (and using a new string to pass as parameter).


Answer to the comment:

  1. because the app can be run in many systems is exactly why you need to measure it.
  2. This is a way to solve your “overall question”. What is the difference between using str.size()>numCol vs is too large? You will need to implement your animation (hint #1: insert a newline character)
  3. as I said before when you start a new line, you start a new string (hint #2: if you extend TextView, you can implement all this in overriding setText). (hint #3: Keep track of the lines created with a static int lines; and use newString.split("\\r?\\n")[lines-1] to check for length).

Leave a Comment