Split a String dynamically based on screen size

Asked

Viewed 335 times

11

I’m working on an android app and at some point I get a string from a web-service that is quite large, and the client wants this String (which will be shown in a Edittext) be divided into multiple parts, forming like a pagination (thought to use a Viewpager to do this navigation).

Well, but the problem is that I don’t know how I can do this "string break" based on the size of the screen, without there being any scroll , or a word being cropped and using as much screen as possible. Not to mention that the font size will be customizable as well, and the user can increase/decrease the font at any time. And all this treatment has to be done dynamically, because this returned string is never the same.

Does anyone have any suggestions?!

2 answers

3

Well, in general lines, you can do the following (the process below should be repeated every time the string changes, or the width or height of the change, 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 that the array lines will contain your original string divided into lines, with no word break (whenever possible).

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

To know how many lines fit at a given height, just use the line height for that source (box 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 want more information, you can see a full example of this here, on a project of mine at Github.

0

Can get the width string and work on 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);
bounds.width();

Source: Soen

Browser other questions tagged

You are not signed in. Login or sign up in order to post.