標籤:應用程式 記事本 字串 中文 標籤
使用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代碼