加载本地文件到 WebView 中

 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();
    }
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值