改变粗体HTML文本的文本颜色

4

我希望在将文本显示到TextView之前更改其文本颜色。

例如,
我从服务器获取的文本如下:

<b>Pratik<b/> has shared photo with <b>you</b>.

现在的要求是以加粗和蓝色文本颜色显示Pratikyou我尝试了使用<span>标签的几种方式,但我没有清晰的方法来显示它。

String htmlBody = "<b>Pratik<b/> has shared photo with <b>you</b>.";
String formattedBody = "<span>" + htmlBody + "</span><style>b { color: #309ce8 ; } span {font-family: 'Avenir', 'Heavy'; font-size: 17; }</style>";

SpannableString text = new SpannableString(formattedBody);
tvMessage.setText(text, TextView.BufferType.SPANNABLE); // This is not working as expected.

tvMessage.setText(Html.fromHtml(htmlBody)); // This is not working as expected.

帮我实现这个目标。


你可以在你的HTML字符串中尝试简单的<font color=#5FCA1C>标签,然后将其设置为Html.fromHtml。 - Rushi M Thakker
你从服务器获取的字符串是对的吗?还有<b></b>标签吗? <b>Pratik</b>与<b>你</b>分享了照片。 - ND1010_
看一下我的帖子,它会帮助你的。 - Raja
3个回答

9
String htmlBody = "<b style='color:blue !important;'>Pratik</b> has shared photo with <b  style='color:blue !important;'>you</b>.";

现在试试,我更新了它。看起来有些东西正在覆盖这个样式。 - slon

3

您的解决方案是:

String styledText = "<b><font color='red'>Pratik</font><b/> has shared photo with <b><font color='red'>you</font></b>";

1
你必须像这样使用。
public void methodName() {
        String html = "Some text <b>here</b>, and some <b>there</b>";
            String result = html.replace("<b>","<font color=\"#ff0000\"><b>").replace("</b>", "</b></font>");
            textView.setText(Html.fromHtml(result));
    }

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