前言


开发中,经常碰到需求是,某个TextView的文字,部分加粗,部分修改颜色,例如

38c4f7dae1c9e71537fffad7c546af57.png

通常我们可以使用Spannable 通过Java代码实现,但是有没有更省时省力的方法呢?能在string.xml 中定义好,直接引入呢?答案是当然有

Android系统提供了对简单的HTML标签的支持,方便开发者设置格式化的文本内容,比如斜体、粗体等。 通过 android.text.Html.fromHtml(String source)


正文

直接给出答案:

<string name="quick_access_staying_offline_content"><![CDATA[To watch <b><font>12,000+ movies, shows</font></b> and more videos, please connect to the internet.]]></string>

实现效果如上图所示,分析string字符串 - <![CDATA[]]将需要整个字符串包裹 - 然后在需要修改的文字加上 <b><font>12,000+ movies, shows</font></b> - 最后在Java代码中使用 textView.setText(Html.fromHtml(String source))

试试修改颜色?

<string name="quick_access_staying_offline_content"><![CDATA[To watch <b><font color="#ff0000">12,000+ movies, shows</font></b> and more videos, please connect to the internet.]]></string>

<font> </font>标签加上 颜色

97932b799b753bb391e754a340c3fc05.png

bingo,轻松实现


支持如下的HTML标签

Supported HTML-Tags

|Tags |Format| |-|-| |b, strong |Bold |i, em, cite, dfn |Italics| |u |Underline| |sub |Subtext| |sup |Supertext| |big |Big| |small |Small| |tt |Monospace| |h1 … h6 |Headlines| |img |Image| |font |Font face and color| |blockquote |For longer quotes| |a |Link| |div, p |Paragraph| |br |Linefeed|


参考如下

https://blog.csdn.net/asdf717/article/details/51850002

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐