前言
开发中,经常碰到需求是,某个TextView的文字,部分加粗,部分修改颜色,例如
通常我们可以使用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>标签加上 颜色
支持如下的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 |
参考如下