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!
Asked
Active
Viewed 1,509 times
3

chRyNaN
- 3,592
- 5
- 46
- 74
-
why won't you try to just manually cause a linebreak where needed by "\n"? Assumed you do not have dynamic text content.. – Droidman Apr 12 '13 at 22:40
-
The text is all dynamic. Maybe I could find out the pixel size of an individual character and knowing how many characters there are, where each word starts, and the size of the screen I could build a new String to set in the textview with appropriate line breaks. But that seems a little much. – chRyNaN Apr 12 '13 at 22:50
-
Take a look on this answer: http://stackoverflow.com/a/18473577/1646326 it is exactly what you need. – meir shapiro Jul 09 '14 at 05:58
1 Answers
1
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(...);
}

David Manpearl
- 12,362
- 8
- 55
- 72