• 转:Android Webview 加载外部html时选择加载本地的js,css等资源文件


    原文地址:http://m.blog.csdn.net/blog/qduningning/43196819

    在使用WebView加载网页的时候,有一些固定的资源文件如js的jquery包,css,图片等资源会比较大,如果直接从网络加载会导致页面加载的比较慢,而且会消耗比较多的流量。所以这些文件应该放在assets里面同app打包。

    要解决这个问题需要用到API 11(HONEYCOMB)提供的shouldInterceptRequest(WebView view, String url) 函数来加载本地资源。在API 21又将这个方法弃用了,是重载一个新的shouldInterceptRequest,需要的参数中将url替换成了成了request。

    比如有一个图片icon.png,这个图片已经放在了assets中,现在加载了一个外部html,就需要直接把assets里面的图片拿出来加载而不需要重新从网络获取。当然可以在html里面将图片链接换成file:///android_asset/icon.png,但是这样这个html就不能在android ,ios,WAP中公用了。

    实现代码:

    webView.setWebViewClient(new WebViewClient() {
    
                @Override
                public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
                    WebResourceResponse response = null;
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
                        response = super.shouldInterceptRequest(view,url);
                        if (url.contains("icon.png")){
                            try {
                                response = new WebResourceResponse("image/png","UTF-8",getAssets().open("icon.png"));
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
    //                return super.shouldInterceptRequest(view, url);
                    return  response;
                }
    
                @TargetApi(Build.VERSION_CODES.LOLLIPOP)
                @Override
                public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
                    WebResourceResponse response = null;
                    response =  super.shouldInterceptRequest(view, request);
                    if (url.contains("icon.png")){
                        try {
                            response = new WebResourceResponse("image/png","UTF-8",getAssets().open("icon.png"));
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    return response;
                }
    }
  • 相关阅读:
    bzoj1901 Zju2112 Dynamic Rankings
    bzoj3932 [CQOI2015]任务查询系统
    poj2104 K-th Number
    splay模板整理
    bzoj1500 [NOI2005]维修数列
    bzoj3223 Tyvj 1729 文艺平衡树
    bzoj1503 [NOI2004]郁闷的出纳员
    bzoj3224 Tyvj 1728 普通平衡树
    用CSS截断字符串
    发布一款仿天猫产品放大镜JQuery插件
  • 原文地址:https://www.cnblogs.com/Cavalry/p/4654880.html
Copyright © 2020-2023  润新知