Determine where Android TextView inserts a line break

I have a rectangular tile and I want to fit the image and some text into it. The image should not overlap the text, and the size of the image and text may vary.

The process must be manually encoded, as we must fine-tune it according to the needs of our customers.

I tried to first measure the displayed text borders with getTextBounds() or measureText() , and then adapting the font size and image size so that they do not overlap.

This works fine if the text is on only one line.

But if a TextView wraps text on multiple lines, I cannot predict the boundaries of the text, since I do not know where TextView will insert automatic line breaks.

How to find out the position in the text where TextView inserts an automatic line break?

Example: Given text

Lorem ipsum dolor sit amet

which will be displayed as

 | Lorem ipsum | | dolor sit amet | 

I need a function that converts

Lorem ipsum dolor sit amet

to

Lorem ipsum \ndolor sit amet

+5
source share
2 answers

The TextView (layout object) has some useful functions for what you are trying to execute:

http://developer.android.com/reference/android/text/Layout.html

take a look at:

getLineCount()

getLineEnd(int line)

You can get a substring for a TextView string based on where the character is in each End string.

You will need to use getViewTreeObserver() to wait for the TextView to be drawn before you can call them and get useful information from them.

Alternatively, you can create a custom TextView that can provide data through built-in methods or by adding a listener to it. An example of a custom TextView that resizes text is shown below:

multi-line text for Android with ellipsis

I used this and made similar changes (for example, what you are trying to do).

+4
source

You probably want to wrap this logic in a custom view (overriding onSizeChanged() ), but you can use the Layout class to check where each line ends:

 textView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { // Remove immediately so it only fires once textView.getViewTreeObserver().removeGlobalOnLayoutListener(this); // View should be laid out, including text placement final Layout layout = textView.getLayout(); float maxLineWidth = 0; // Loop over all the lines and do whatever you need with // the width of the line for (int i = 0; i < layout.getLineCount(); i++) { maxLineWidth = Math.max(maxLineWidth, layout.getLineWidth(i)); } } }); 
+3
source

Source: https://habr.com/ru/post/1204659/


All Articles