How do I prevent a word in a TextView
from 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(" ", " ");
tv.setText(Html.fromHtml(fullString));
tv.setTextSize(32f);
tv.setTextColor(getResources().getColor(R.color.text));
layout.addView(tv);
the problem is in following line
fullString = fullString.replaceAll(" ", " ");
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
The problem with your code is this line:
fullString = fullString.replaceAll(" ", " ");
By doing this, you replace all "normal" spaces with non-breakable spaces ( 
). Since these spaces are non-breakable, they prevent a line break.
Just remove this line and the words won't break in half anymore.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With