0

I am developing an android application where I would like to fit text on different screen sizes. There is one TextView for which I want to estimate appropriate height so that text would fit inside. The text contains new line characters ("\n"):

        TextView table3team1 ...
        ....
        Paint paint = new Paint();
        Rect bounds = new Rect();
        paint.setTypeface(table3team1.getTypeface());
        paint.setTextSize((float)scheddateminsize);
        String text = table3team1.getText().toString();
        paint.getTextBounds(text, 0, text.length(), bounds);

        int maxlines = 0;
        int lines = text.length() - text.replace("\n", "").length();
        maxlines = lines;

        int height_in_pixels = maxlines * bounds.height(); 

        table3team1.setMinHeight(height_in_pixels);
        table3team2.setMinHeight(height_in_pixels);

In the code above I estimate the text height by multiplying amount of lines of text (number of new line characters) by estimated height of one line (the paint.getTextBounds function). It does work perfectly when each line of the text fits in one line. But if the text is longer, it automatically goes to next line thus making the number of lines more than I thought it would be and text doesn't fit into boundaries: Example

You can see from that image how at the bottom some text didn't fit. Is it possible to get the boundaries of the text including height which considers the new line characters as well as new line due to text not fitting into one line? Or is there any other way to do it?

maximus
  • 4,201
  • 15
  • 64
  • 117
  • Use [`StaticLayout`](https://developer.android.com/reference/android/text/StaticLayout). – Mike M. Apr 27 '18 at 10:05
  • The approach you've been trying use is tedious and error prone. I recommend to make use of the algorithm proposed in [this answer](https://stackoverflow.com/a/32096884/3290339). You gonna need to take only the 1st page of all the pages calculated. – Onik Apr 27 '18 at 20:21

0 Answers0