如何从TextView中删除&nbsp

4
我需要在TextView中替换&nbps。我可以简单地使用String.replace(),但可能有更好的解决方案?

String.replace() 是摆脱这些问题的唯一方法 :) - Ali Imran
2
你可以将Html.fromHtml(string)设置到TextView中并进行检查。 - Sumant
1
Html.fromHtml(String) 对我来说很完美,请回答以便我接受。 - Eugene
2
除非您有其他要解释的HTML,否则使用fromHtml() 替换为空格就像用Buick打苍蝇一样。使用replaceAll()应该更便宜。 - CommonsWare
2个回答

3

尝试使用Pattern.compile:

Pattern p = Pattern.compile("&nbps");
String tempstr = "I love &nbps  &nbps.";

Matcher matcher = p.matcher(tempstr);
String tmp = matcher.replaceAll("Android");

你可以查看有关String.replace和matcher.replace性能的帖子。 String replaceAll() vs. Matcher replaceAll()(性能差异)

2
String.replace() 的性能表现有何不同? - Ali Imran
@AliImran:我不确定这段代码的性能如何,但我确信它在所有情况下都能正常工作。 - ρяσѕρєя K
这是在当前字符串中替换子字符串的另一种方法。 - ρяσѕρєя K
我以前知道这个,但从来没有将它优先考虑过简单的 String.replace() 方法 :) - Ali Imran
@AliImran:在某些情况下,String.replace()无法正常工作,那么你只有这个选项。你可以查看我的编辑答案。 - ρяσѕρєя K
1
是的,你说得对,因为有时候 String.replace() 不起作用。 - Ali Imran

1

尝试使用此函数:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            mDescription.setText(Html.fromHtml("Your Text", Html.FROM_HTML_MODE_LEGACY));
        } else {
            mDescription.setText(Html.fromHtml("Your Text"));
        }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接