android html.fromhtml 颜色,Android - Html.fromHtml handle background color

博客探讨了在不使用WebView的情况下,如何在TextView中显示带有背景颜色的HTML文本。作者遇到的问题是Html.fromHtml()方法不支持字体标签的背景属性。为了解决这个问题,他们尝试了自定义标签处理器,但发现只能获取到标签而无法获取属性。最终,通过编写代码片段来手动处理文本并设置背景颜色,实现了在TextView中正确显示HTML文本背景的效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I have html text that I need to display in TextView. The html may look like this -

Text with background and color

Html.fromHtml doesn't support any attribute other than color for font tag. But we absolutely must show the background. I could write a custom tag handler but the attributes are not passed in, only the tag is passed in.

What is the best way to achieve this ?

NOTE : Cant use Webview.

I tried the code below. If I set raw on the text, it works, but if i process it further and pass it to Html.fromHtml, it doesnt show the background.

public static final String sText =

"Background on part 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());

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值