Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent word from being broken in TextView

How do I prevent a word in a TextViewfrom breaking in half when it doesn't fit on the current line and instead move to the next line.

|android goo|
|gle kitkat |

should instead be

|android    |
|google     |
|kitkat     |

The TextView is currently added to a RelativeLayout using this code:

TextView tv = new TextView(this);
RelativeLayout.LayoutParams layoutParams = new  RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);

float scale = getResources().getDisplayMetrics().density;
int dpAsPixels = (int) (16*scale + 0.5f);
tv.setPadding(dpAsPixels, 0, dpAsPixels, 0);

tv.setLayoutParams(layoutParams);

String fullString = "<b>" + user + ":</b> " + text;
fullString = fullString.replaceAll("\n", "<br />");
fullString = fullString.replaceAll(" ", "&#160");
tv.setText(Html.fromHtml(fullString));
tv.setTextSize(32f);
tv.setTextColor(getResources().getColor(R.color.text));

layout.addView(tv);
like image 412
Oskar Persson Avatar asked May 09 '15 16:05

Oskar Persson


2 Answers

the problem is in following line

fullString = fullString.replaceAll(" ", "&#160");

remove it and it will work as you need, you don't need to replace space with html code, fromHtml will do it for you

like image 171
Vilen Avatar answered Nov 15 '22 15:11

Vilen


The problem with your code is this line:

fullString = fullString.replaceAll(" ", "&#160");

By doing this, you replace all "normal" spaces with non-breakable spaces (&nbsp). Since these spaces are non-breakable, they prevent a line break.

Just remove this line and the words won't break in half anymore.

like image 21
Manuel Allenspach Avatar answered Nov 15 '22 13:11

Manuel Allenspach