使用WebView載入HTML代碼

來源:互聯網
上載者:User

標籤:應用程式   記事本   字串   中文   標籤   

    使用EditText顯示HTML字串時,EditText不會對HTML標籤進行任何解析,而是直接把所有HTML標籤都顯示出來-----就像用普通記事本顯示一樣;如果應用程式想重新對HTML字串進行解析、當成HTML頁面來顯示,也是可以的。

    WebView提供的loadData(String  data ,  String  mimeType ,  String  encoding)方法,該方法可用於載入並顯示HTML代碼,但在實際使用過程中,當它載入包含中文HTML內容時,WebView將會顯示亂碼。

    WebView還提供了一個loadDataWithBaseURL(String   baseUrl , String  data ,  String  mimeType ,  String  encoding , String  historyUrl)方法,該方法是loadData(String  data ,  String  mimeType ,  String  encoding)方法的增強版,它不會產生亂碼。

    1、data:指定需要載入的HTML代碼。

    2、mimeType:指定HTML代碼的MIME類型,對於HTML代碼可指定為text/html。

    3、encoding:指定HTML代碼編碼所用的字元集。比如指定為GBK。

import android.os.Bundle;import android.app.Activity;import android.view.Menu;import android.webkit.WebView;public class ViewHtml extends Activity {  WebView show;  @Override  protected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_view_html);    //擷取程式中的WebView組件    show = (WebView) findViewById(R.id.show);    StringBuilder sb = new StringBuilder();    //拼接一段HTML代碼    sb.append("<html>");    sb.append("<head>");    sb.append("<title>Our Love</title>");    sb.append("</head>");    sb.append("<body>");    sb.append("<h2>Love<a href=\"http://love.shiningchen.cc\">"            +"Shining</a></h2>");    sb.append("</body>");    sb.append("</html>");    //使用簡單的loadData方法會導致亂碼,可能是Android API的Bug    //show.loadData(sb.toString(), "text/html", "utf-8");    //載入、並顯示HTML代碼    show.loadDataWithBaseURL(null,sb.toString(), "text/html", "utf-8", null);  }}


本文出自 “梁肖技術中心” 部落格,請務必保留此出處http://liangxiao.blog.51cto.com/3626612/1889694

使用WebView載入HTML代碼

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.