Android WebView 載入HTML程式碼
阿新 • • 發佈:2019-01-31
<uses-permission android:name="android.permission.INTERNET" />
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width ="match_parent"
android:layout_height="match_parent"
tools:context="shortcut.song.com.myapplication.ViewHtmlActivity">
<WebView
android:id="@+id/web_html"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
package shortcut.song.com.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
public class ViewHtmlActivity extends AppCompatActivity {
WebView webView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super .onCreate(savedInstanceState);
setContentView(R.layout.activity_view_html);
webView = (WebView)findViewById(R.id.web_html);
StringBuilder sb = new StringBuilder();
// 拼接一段HTML程式碼
sb.append("<html>");
sb.append("<head>");
sb.append("<title>Hello</title>");
sb.append("</head");
sb.append("<body");
sb.append("<h2>歡迎來到中國 welcome to china</h2>");
sb.append("</body>");
sb.append("</html>");
// 使用簡單的loadData方法會導致亂碼
//webView.loadData(sb.toString(), "text/html", "utf-8");
// 載入並顯示HTML程式碼
webView.loadDataWithBaseURL(null, sb.toString(), "text/html", "utf-8", null);
}
}