Divide a String dynamically based on screen size


I'm working on an android app and at some point I get a String from a web-service that is pretty big, and the client wants that String (which will be shown in an EditText ) is divided into multiple parts, forming a pagination type (I thought of using a ViewPager to do this navigation).

Well, but the problem is that I do not know how I can do this "breaking the string" based on the size of the screen, without scrolling, or that a word is cut and using as much of the screen as possible. Not to mention that the font size will be customizable too, and the user can increase / decrease the font at any time. And all this handling has to be done dynamically, because this returned String is never the same.

Does anyone have any suggestions?!

asked by anonymous 18.05.2015 / 20:43

2 answers


Well, in general terms, you can do the following (the process below should be repeated every time the string changes, or the width or height of the font changes, or the font size changes):

Paint paint = new Paint();
//defina sua fonte aqui, caso deseje
paint.setTextSize(<TAMANHO DA FONTE EM PIXELS>);

StaticLayout layout = new StaticLayout(<SUA STRING>, paint, <LARGURA DISPONÍVEL>, Alignment.ALIGN_NORMAL, 1, 0, false);

int lineCount = layout.getLineCount();
String lines[] = new String[lineCount];
for (int i = 0; i < lineCount; i++)
    lines[i] = <SUA STRING>.substring(layout.getLineStart(i), layout.getLineEnd(i));

With this, the array lines will contain its original string divided into lines, without breaking words (whenever possible).

From there, you can draw the lines on the screen manually using the Canvas provided in the onDraw methods of the View class, or you can concatenate any of these rows, and assign that result to a TextView .

To know how many rows fit at a given height, just use the line height for that font ( box ):

Paint paint = new Paint();
//defina sua fonte aqui, caso deseje
paint.setTextSize(<TAMANHO DA FONTE EM PIXELS>);

Paint.FontMetrics fm = paint.getFontMetrics();
int lineHeight = (int)(fm.descent - fm.ascent + 0.5f);

int linesPerView = <ALTURA DA VIEW> / lineHeight;

If you'd like more information, you can see a complete example of this here, in a project of mine in GitHub .

26.07.2015 / 17:15

You can get the width of the string and play on top of it.

Paint mPaint = new Paint();
mPaint.setTextSize(/*put here ur size*/);
mPaint.setTypeface(/* put here ur font type */);
Rect bounds = new Rect();
mPaint.getTextBounds(text, 0, text.length(), bounds);

Source: SOen

18.05.2015 / 20:46