我正在尝试将html放入TextView中。一切都很完美,这是我的代码。
String htmlTxt = "<p>Hellllo</p>"; // the html is form an API
Spanned html = Html.fromHtml(htmlTxt);
myTextView.setText(html);这将使用正确的html设置我的TextView。但我的问题是,有一个
标记中,进入TextView的结果文本在末尾有一个"\n“,所以它将我的文本视图的高度推高到超出它应有的高度。
由于它是一个跨区变量,我不能应用正则表达式replace来删除"\n",如果我要将其转换为字符串,然后应用正则表达式,我将失去让html锚点正常工作的功能。
有没有人知道从"Spanned“变量中删除结束换行符的解决方案?
发布于 2012-04-17 16:12:34
回答得好,@Christine。今天下午,我编写了一个类似的函数来删除CharSequence中的尾随空格:
/** Trims trailing whitespace. Removes any of these characters:
* 0009, HORIZONTAL TABULATION
* 000A, LINE FEED
* 000B, VERTICAL TABULATION
* 000C, FORM FEED
* 000D, CARRIAGE RETURN
* 001C, FILE SEPARATOR
* 001D, GROUP SEPARATOR
* 001E, RECORD SEPARATOR
* 001F, UNIT SEPARATOR
* @return "" if source is null, otherwise string with all trailing whitespace removed
*/
public static CharSequence trimTrailingWhitespace(CharSequence source) {
if(source == null)
return "";
int i = source.length();
// loop back to the first non-whitespace character
while(--i >= 0 && Character.isWhitespace(source.charAt(i))) {
}
return source.subSequence(0, i+1);
}发布于 2016-03-04 05:32:16
您可以尝试这样做:
Spanned htmlDescription = Html.fromHtml(textWithHtml);
String descriptionWithOutExtraSpace = new String(htmlDescription.toString()).trim();
textView.setText(htmlDescription.subSequence(0, descriptionWithOutExtraSpace.length()));发布于 2014-07-03 20:03:03
你可以使用这几行...完全有效;)
我知道你的问题已经解决了,但也许有人会觉得这很有用。
try{
string= replceLast(string,"<p dir=\"ltr\">", "");
string=replceLast(string,"</p>", "");
}catch (Exception e) {}这是replaceLast ..。
public String replceLast(String yourString, String frist,String second)
{
StringBuilder b = new StringBuilder(yourString);
b.replace(yourString.lastIndexOf(frist), yourString.lastIndexOf(frist)+frist.length(),second );
return b.toString();
}https://stackoverflow.com/questions/9589381
复制相似问题