Avik Banerjee
Avik Banerjee

Reputation: 13

Calculate max number of characters (having predefined size eg 20dp) that will fit in a text view android

I need to calculate how many characters (having pre-defined size eg 20dp) will fit on the text view to divide the long text into different Views? Like any reader app

I'm using the following code that works fine for a single line. My question is how to determine the max number of lines that will fit in text view in various screen sizes?

string abc = "This string is a loooong string";
final float densityMultiplier = getResources().getDisplayMetrics().density;
final float scaledPx = 20 * densityMultiplier;

int numChars;
Paint paint = txtArea.getPaint();
paint.setTextSize(scaledPx);
for (numChars = 1; numChars <= abc.length(); ++numChars)
{
     if (paint.measureText(abc, 0, numChars) >= screenWidthDp)
     {
          break;
     }
}

Upvotes: 1

Views: 93

Answers (1)

StenSoft
StenSoft

Reputation: 9609

Simply use TextView.getLineHeight() to get height of a line

Upvotes: 1

Related Questions