use*_*916 4 html android textview
我有需要在 TextView 中显示的 html 文本。html 可能看起来像这样 -
<font color="#AFEEEE"><font style="background-color: rgb(255,140,0);">Text with background and color</font></font>
Run Code Online (Sandbox Code Playgroud)
Html.fromHtml 不支持字体标签颜色以外的任何属性。但我们绝对必须展示背景。我可以编写一个自定义标记处理程序,但不传入属性,仅传入标记。实现此目的的最佳方法是什么?
注意:无法使用 Webview。
我尝试了下面的代码。如果我在文本上设置 raw,它会起作用,但如果我进一步处理它并将其传递给 Html.fromHtml,它不会显示背景。
public static final String sText =
"Background on <font style=\"background-color: rgb(255,255,0);\">pa</font>rt text only";
Pattern pattern = Pattern.compile(BACKGROUND_PATTERN);
Matcher matcher = pattern.matcher(sText);
SpannableString raw = new SpannableString(sText);
BackgroundColorSpan[] spans =
raw.getSpans(0, raw.length(), BackgroundColorSpan.class);
for (BackgroundColorSpan span : spans) {
raw.removeSpan(span);
}
while (matcher.find()) {
raw.setSpan(new BackgroundColorSpan(0xFF8B008B),
matcher.start(2), matcher.start(2) + matcher.group(2).length(),
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
sText = raw.toString();
final Spanned convertedHtml =
Html.fromHtml(sText, ig, new myTagHandler());
Run Code Online (Sandbox Code Playgroud)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
String str = "<span style=\"background-color:#f3f402;\">" + TEXT TO HIGHLIGHT + "</span>";
textView.setText(Html.fromHtml(str, Html.FROM_HTML_MODE_LEGACY));
} else {
String str = "<font color='#f3f402'>" + TEXT TO HIGHLIGHT + "</font>";
textView.setText(Html.fromHtml(str));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6703 次 |
| 最近记录: |