Android WebView 加载HTML代码

这里写图片描述

<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);

    }
}

运行效果:

这里写图片描述


版权声明:本文为u013420428原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。