[关闭]
@xiaoyixy 2015-10-06T12:08:25.000000Z 字数 1571 阅读 2778

加载本地文件到 WebView 中

Hybrid


    Android 的 WebView 提供了一系列非常灵活的API,可从多种源中加载文件。但是,由于同源规则限制了可向 web 浏览器加载数据的位置,在一些特定的情况下我们不得不重新调整 WebView 的行为。

Ⅰ 加载一个给定 URL 的 res/drawable 本地文件到WebView 中:

    String html = "<!DOCTYPE html>";
    html += "<head><title>Loading files from res/drawable directory</title></head>";
    html += "<body><img src=\"logo.png\" />/body>";
    html += "</html>";
    WebView.loadDataWithBaseURL("file:///android_res/drawable/", html, "text/html",
    "UTF-8", null);

Ⅱ 加载一个给定 URL 的 SD 卡本地文件到 WebView 中:

    String base = Environment.getExternalStorageDirectory().getAbsolutePath()
    .toString();
    String imagePath = "file://"+ base + "/logo.png";
    String html = "<!DOCTYPE html>";
    html += "<head><title>Loading files from SDCard</title></head>";
    html += "<body><img src=\""+ imagePath + "\" />/body>";
    html += "</html>";
    WebView.loadDataWithBaseURL("", html, "text/html","UTF-8", null);
注意:
    以上两个方案只有在 API 2.2及以上才能支持。API 2.2以下一个可选择的方案是读取文件到字符串缓冲区。

Ⅲ 通过用 java 读取文件内容并把数据传送到 WebView 的方法把数据加载到 WebView 中:

    // Load an html file
    String html = loadFileFromSDCard("file:///sdcard/oreilly/book/logo.png");
    WebView.loadDataWithBaseURL("", html, "text/html", "UTF-8", null);
或:
    // Load an image file
    String pngData = loadFileFromAssets("file:///android_asset/images/logo.png");
    WebView.loadData(pngData, "image/png", "UTF-8");

Ⅳ 从 res/raw 目录读取文件:
    如果你需要从 res/raw 目录读取一个文件(例如,home.html)并且在 WebView 中显示,你需要把资源的 ID (例如,R.raw.home)传递到你的读取函数然后把它转化为字符串的形式。

    WebView.loadData(getRawFileFromResource(R.raw.home), "text/html", "UTF-8");
    private String getRawFileFromResource(int resourceId) {
        StringBuilder sb = new StringBuilder();
        Scanner s = new Scanner(getResources().openRawResource(resourceId));
        while (s.hasNextLine()) {
            sb.append(s.nextLine() + "\n");
        }
        return sb.toString();
    }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注