我正在尝试使用 html 将某些文本格式化(添加样式)并将其设置为 TextView 的文本
Spanned text =Html.fromHtml(""+newAllText);
hello.setText(text, TextView.BufferType.SPANNABLE);
但是 Html() 方法返回的是已删除所有空格的 Spanned 字符串。我试过使用 html 标签,例如 <pre>
但它没有帮助..
它应该像this 一样很好地显示(后来使用 from Html() 方法删除了 html 标签)但是所有的空格都被删除了,它看起来像 this (当它在 ui 中设置为文本时,它看起来像一个大的连续段落)。
有人知道吗?
以防万一有人想看完整代码:
String SelectedSentence =allText.substring(lastPoint, nextPoint);
String highlighted = "<font color='red'>"+SelectedSentence+"</font>";
StringBuilder newAllText = new StringBuilder(allText);
newAllText.delete(lastPoint, nextPoint+1);
newAllText.insert(lastPoint,highlighted);
newAllText = new StringBuilder("<pre>"+newAllText+"</pre>");
Spanned text =Html.fromHtml(""+newAllText);
hello.setText(text, TextView.BufferType.SPANNABLE);
lastPoint = nextPoint;
最佳答案
好吧,我放弃了整个 HTML 文本样式化方法,只使用 SpannableStringBuilder 来获得我想要的相同效果
highlighted = new SpannableStringBuilder(sb);
highlighted.removeSpan(new BackgroundColorSpan(Color.YELLOW));
highlighted.setSpan(new BackgroundColorSpan(Color.YELLOW),lastPoint, nextPoint, 0);
关于java - 在android中的textview中保留空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12363110/