使用Html.fromHTML以< A>标签将无法色彩!色彩、标签、fromHTML、Html

2023-09-06 14:09:32 作者:爱洗澡的魚

我试图使用Android Html.fromHtml方法来解析像@鸣叫文本在它提到。不过,我有当前用户的用户名和我想强调这给用户作为是他们自己。

I'm trying to use the Android Html.fromHtml method to parse a text like a tweet with @ mentions in it. However, I have the username of the current user and I wish to highlight this to the user as being themselves.

我想这个code,它不工作:

I'm trying to with this code, which doesn't work:

在= in.replace(@+ u.username,@<字体背景=#0099FF颜色=#FFF>< A HREF ='dailybooth://用户/ +                    u.username +'>中+ u.username +< / A>< / FONT>中);

在理论上,我认为它应该工作,但它不色了!

In theory, I think it should work, however it doesn't color at all!

推荐答案

这竟然是一个谎言。

无论是字体标记,也没有内嵌样式的 A 标记为我工作。 我不得不求助于使用Spannables直接

Neither the font tag nor inline styles on the a tag worked for me. I had to resort to using Spannables directly:

TextView text = (TextView) findViewById(R.id.text);
text.setText("");
String linkName = "@appamatto";
String linkUrl = "http://twitter.com/appamatto"
SpannableString str = SpannableString.valueOf(linkName);
str.setSpan(new URLSpan(linkUrl), 0, linkName.length(),
    Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
str.setSpan(new ForegroundColorSpan(0xffffffff), 0, linkName.length(),
    Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
str.setSpan(new BackgroundColorSpan(0xff0099ff), 0, linkName.length(),
    Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
text.append(str);

这意志,例如,设置你想要的方式链接的颜色。你可以寻找其他Spannables在 android.text.style 实现其他效果。

This will, for example, set the colors of the link in the way you wanted. You can look for other Spannables in android.text.style to achieve other effects.

修改作为替代,你可以这样做:

Edit for replace you could do something like:

String[] components = in.split("@" + u.username, -1);
text.append(components[0]);
for (int i = 1; i < components.length; i++) {
    text.append(str); // using the spannable from above
    text.append(components[i]);
}

在-1 拆分()是你将需要处理的比赛在字符串的结尾来了,按照拆分文档。

The -1 in split() is what you would need to deal with matches coming at the end of strings, as per the split docs.