Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to control when TextView sends String to new line?

When a word in a String from a TextView is too large to fit on the same line as the prior words it skips to the next line. This proves to be very useful. However, this puts me in a dilemma. My String, for my particular reasons, needs to have a space in between each letter of a word and two spaces in between words. Because of this the TextView will split words having one piece on one line and the other piece on the next. So, I'm thinking I may have to create a custom View that extends TextView and override the way it skips to the next line. But taking a look at the class documents for textview I can't find a way I would do this. So, any help, advice or suggestions will be greatly appreciated! Thanks!

like image 607
chRyNaN Avatar asked Jan 30 '26 20:01

chRyNaN


1 Answers

You can override TextView with a few modifications.

The basic strategy will be to override the onDraw() method and custom paint your text. You will also have to override onMeasure().

Within onDraw() you will pre-process the custom words in your string and insert newline characters (\n) as necessary.

Loop through the words in your text and compare measureText(String) with the current width of your TextView to determine where to insert the newlines. Don't forget to take into account "padding".

Example:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    // TODO Auto-generated method stub
    super.onMeasure(getSuggestedMinimumWidth(), getSuggestedMinimumHeight());
}

@Override
protected void onDraw(Canvas canvas) {
    // preprocess your text
    canvas.drawText(...);
}
like image 122
David Manpearl Avatar answered Feb 01 '26 09:02

David Manpearl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!