WebView 提供 loadData(String data, String mimeType, String encoding) : 方法,該方法可以用於加載並顯示HRML代碼,實際應用過程中 存在一個問題,,當他加載包含中文的HTML內容時,WebView將會顯示亂碼.
幸好WebView還提供了一個 loadDataWithBaseURL(String baseUrl, String data, String mimeType, String encoding, String historyUrl) : 方法,該方法是loadData()方法的增強版,它不會產生亂碼.
loadDataWithBaseURL(String baseUrl, String data, String mimeType, String encoding, String historyUrl) : 幾個參數的簡單說明.
- data : 指定需要加載的HTML 代碼.
- mimeType :指定HTML 代碼的 MIME類型.對於HTML代碼可指定爲text/html .
- encoding :指定HTML 代碼的代碼編碼所用的字符集.比如指定 UTF-8.
package com.net.webview;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.webkit.WebView;
public class ViewHtmlActivity extends AppCompatActivity {
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> 歡迎您 </title>");
sb.append("</head>");
sb.append("<body>");
sb.append("<h2> 歡迎您訪問<a href=\"http://www.cctv.com\">"
+ "Java聯盟</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);
}
}