項目中往往需要顯示一段文本,如果對文本需要特定的效果,就要寫自訂的span,這樣的工作量會變得很大,目前android支援html格式的文本。提供了兩個介面,下面我們就來看一下怎麼使用。
1. Spanned android.text.Html.fromHtml(String source) //輸入的參數為(html格式的文本)
目前android不支援全部的html的標籤,目前只支援與文本顯示和段落等標籤,對於圖片和其他的多媒體,還有一些自訂標籤不能識別;
例子:
TextView t3 = (TextView) findViewById(R.id.text3);
t3.setText(Html.fromHtml( "<b>text3:</b> Text with a " + "<a href=\"http://www.google.com\">link</a> " +"created in the Java source code using HTML."));
另外也可以在string.xml中使用,但是要用用<!–cdata–>去轉義。如下例子:
<string name="htmlFormattedText">
<![CDATA[
Text with markup for [b]bold[/b]
and [i]italic[/i] text.
There is also support for a
<tt>teletype-style</tt> font.
But no use for the <code>code</code>
tag!
]]></string>
TextView view = (TextView)findViewById(R.id.sampleText);
String formattedText = getString(R.string.htmlFormattedText);
Spanned result = Html.fromHtml(formattedText);
view.setText(result);
2.Spanned android.text.Html.fromHtml(String source, ImageGetter imageGetter, TagHandler tagHandler)
Source: 需處理的html文本
imageGetter :對圖片處理(處理html中的圖片標籤)
tagHandler :對標籤進行處理(相當於自訂的標籤處理,在這裡面可以處理自訂的標籤)
具體不細說,大家感興趣可以自行學習;在實際項目裡我們就可以使用第一種方式來替代之前我們用的自訂span了。