In my Android layout, I have a TextView that uses half of the available width of the screen. At runtime I set the text to a (long) email address. For instance:
googleandroiddeveloper@gmail.com
If the text does not fit into one line, Android inserts a line break, which is the desired behavior. However, the position of the line break is before the first character that does not fit in the line. The result can be something like this:
googleandroiddeveloper@gmai
l.com
I think, this is kind of ugly, especially in email addresses. I want the line break to appear right before the @ character:
googleandroiddeveloper
@gmail.com
Of course, i could add a \n in my strings.xml. But then the email address would use two lines in every case, even if it would fit into one line.
I already thought I had found a solution in adding a ZERO WIDTH SPACE (\u200B) to the email address.
<string name="email">googleandroiddeveloper\u200B@gmail.com</string>
But other than with standard spaces, Android does not detect the special space character as a breakable space and consequentially does not add a line break at this point.
As I am dealing with a lot of email addresses in multiple places of my application, I am searching for a solution to add a breakable and invisible space before the @ character, so Android wraps the email address if does not fit into one line.
@Luksprog’s solution is very good and solves the problem in many cases. However, I modified the class at several points, to make it even better. These are the modifications:
onSizeChangedinstead ofonMeasurefor checking and manipulating the text, because there are problems withonMeasurewhen usingLinearLayoutwithlayout_weight.getPaddingLeft()andgetPaddingRight()afterAtI replacedpositionwithposition + 1, otherwise the resulting email address contains two@.Code:
Here is a screenshot of
EmailTextViewcompared to defaultTextView:For all email addresses it works as I expected. The last address is not changed because the text before the
@is already too wide, so the system breaks it before and the thereby the email address is kind of messed up anyway, so there is no need to include another line break.