android Html.fromHtml使用詳解

來源:互聯網
上載者:User

項目中往往需要顯示一段文本,如果對文本需要特定的效果,就要寫自訂的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了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.