項目中時長會遇到TextView 顯示的文本要用到不同的樣式,這時如果用很多個TextView組合會顯得比較low,而且也比叫浪費時間,通常我們利用Html相關的API:
String text = "<font color='#333333'><Strong>"+
Hello+
"</Strong></font>
<font color='#666666'>"+
World+
"</font>";
textView1.setText(Html.fromHtml(text));
實際應用中,我們通常會將文案寫在資源文件中,然後在代碼中調用,但我們會發現在資源文件中寫的樣式卻沒有效果:
<string name="test_1">
This is a <font color="#4fc3f7"><a href="https://www.baidu.com">Hello world</a>
</font>yeah,yeah,fuck!
</string>
textView1.setText(Html.fromHtml(getString(R.string.test_1)));
怎麼解決這個問題呢?其實很簡單,在資源文件裏相應的文案上加上 <![CDATA[]]>:
<string name="test_1">
<![CDATA[
This is a <font color="#4fc3f7" size="24px"><a href="https://www.baidu.com">Test
case</a></font>yeah,yeah,fuck!
]]>
</string>
這樣在資源文件裏寫的樣式就成正確顯示了,那麼這是什麼意思呢?
<![CDATA[]]> 包含的內容將表示爲純文本,這樣Html的API就能正確解析這段文案了。