How to Prevent a Pair of Words From Being Split Onto Separate Lines in Android TextView
The Short Answer: If you have a string with a space in it that should not be broken up when wrapping text, replace the space character with a Unicode non-breaking space: '\u00A0'. This character is rendered as a space, but is not treated by line-breaker logic as a word-break.
The Longer Version
I was just working on an Android app where I want a brief time-stamp to appear after a headline, to indicate how old the headline is. The headline appears in large black text, and is immediately followed by a space, a bullet, another space, and the age of the headline, like "15m" for fifteen minutes, "2h" for two hours, etc. When the headline is long enough to wrap onto a second line, I want to make sure that the bullet and the time-stamp remain together on the same line -- to avoid having the time-stamp orphaned on its own line.
My first thought was to look for a span class that could indicate to the TextView that the words within the span should never be separated across lines. Finding nothing, I started thinking maybe there was a way to write a custom LineBreaker that would extend from the standard class but have special rules about where to break.
I chatted with an iOS developer who was working in parallel, and he didn't have a ready solution to this problem on his side, either. I came away thinking, "This has to be a common problem. And it feels familiar -- I just can't remember the solution."
I did some more searching, and came across this Stack Overflow question -- which was exactly what I was looking for: How to influence linebreak in Android Textview. I suddenly realized this was familiar to me because of the special non-breaking space in HTML: . It's just been so long since I last did any significant web development that I forgot about this simple solution. It's a relief to find that the same pattern is followed in Android.
If you're thinking about doing the same thing with non-breaking hyphens, be careful: this will likely break any search feature that would normally match on a hyphen in a search term.
If you found this helpful, you'd like to thank me, and you enjoy reading science fiction -- or know someone who does -- buy my book!