Android WebWiew 使用详解

来源:互联网 发布:c语言a i 什么意思 编辑:程序博客网 时间:2024/05/17 00:07

WebView 从字面意思上来看,第一他是个Web,第二他是个View。
那么Web的工作就是加载网络资源。
View就是Android的控件,在容器中进行内容的显示。
合起来就是加载网络资源,在Android中进行显示。

那么加载网络资源最重要的就是loadUrl 即加载的地址。
那么最核心的方法就是:

public void loadUrl(String url) {}

但是和加载图片一样,加载数据就涉及到对加载选项的配置,比如说缓存信息的设置等等。
那么为了让WebView更好的工作,我们就需要了解具体有那些配置项,将配置项设置好,就可以让他更好的进行工作。

接下来我们从Layout开始讲解一下,从定义到使用,我们要进行那些工作,和这些工作都是干什么的。

第一步在Layout中进行声明;

<WebViewandroid:id="@+id/myWeb"android:layout_width="match_parent"android:layout_height="wrap_content" />

非常简单,只需三行,其他的在程序内部搞定!

第二步得到我们的VebView对象

webView = (WebView) findViewById(R.id.webview);

第三步就是大家最关心的调用加载网络数据

webView.loadUrl("http://www.baidu.com");

但是如果直接使用此方法,会调用系统默认的浏览器进行数据加载。(其实我们是需要在我们的容器里进行数据的显示而不是打开浏览器。因为大多数时候是使用这个控件显示一些商品的信息,打开浏览器的体验并不是很好!)

那么如何实现那,WebView易已经想好了,那么我就使用这个方法。

myWeb.setWebViewClient(new WebViewClient() {            @Override            public boolean shouldOverrideUrlLoading(WebView view, String url) {                view.loadUrl(url);                return super.shouldOverrideUrlLoading(view, url);            }            @Override            public void onReceivedError(WebView view, int errorCode,                    String description, String failingUrl) {                super.onReceivedError(view, errorCode, description, failingUrl);                myWeb.loadUrl("file:///android_asset/err.html");        myWeb.setVisibility(View.GONE);                 }        });

注:loadurl(url)依然需要使用。
shouldOverrideUrlLoading()
一般情况下我们不需要重写,这个函数有一个返回值,当为false时的意思使我们不用管, 当前的webView正在加载这个Url。当返回true就让我们自己操作。

/** * Report an error to the host application. These errors are unrecoverable * (i.e. the main resource is unavailable). The errorCode parameter * corresponds to one of the ERROR_* constants. * @param view The WebView that is initiating the callback. * @param errorCode The error code corresponding to an ERROR_* value. * @param description A String describing the error. * @param failingUrl The url that failed to load. * @deprecated Use {@link #onReceivedError(WebView, WebResourceRequest, WebResourceError) *             onReceivedError(WebView, WebResourceRequest, WebResourceError)} instead. */

onReceivedError()
当接收的网络信息错误时,就会调用这个方法。那么我们需要指向一个备用站,或者将这个WebView进行隐藏。

public void onPageFinished(WebView view, String url) {}

当加载完成时进行调用,但需要注意的是。

/** * When onPageFinished() is called, the * rendering picture may not be updated yet. To get the notification for the * new Picture, use {@link WebView.PictureListener#onNewPicture}. */

翻译过来就是,当你的网页被加载完成时,被渲染的图片(缓冲)可能还没有加载好,需要进一步对WebView的PictureListener pic方法进行再次监听,已实现完全加载完成时,进行操作。

/** * Notify the host application that the WebView will load the resource * specified by the given url. * * @param view The WebView that is initiating the callback. * @param url The url of the resource the WebView will load. */public void onLoadResource(WebView view, String url) {}

这个函数是这要加载资源就会被调用。
我们可以自定义一个小动画,在里面,避免空白页带来的尴尬。

/** * Tell the host application the current progress of loading a page. * @param view The WebView that initiated the callback. * @param newProgress Current page loading progress, represented by *                    an integer between 0 and 100. */public void onProgressChanged(WebView view, int newProgress) {}

那这里我们又有一个需求:我们要有一个进度条,那我们怎么知道时时的加载进度呢,就不是在WebViewClient类中了,而是在WebChromeClient中onProgressChanged()。

说道了WebChromeClient,那么他还有一些常用的函数。

/** * Notify the host application of a change in the document title. * @param view The WebView that initiated the callback. * @param title A String containing the new title of the document. */public void onReceivedTitle(WebView view, String title) {}/** * Notify the host application of a new favicon for the current page. * @param view The WebView that initiated the callback. * @param icon A Bitmap containing the favicon for the current page. */public void onReceivedIcon(WebView view, Bitmap icon) {}

一个是可以获取网页的title,一个是可以title旁边的icon。
然后说一下webview缓存问题:有时候我们有缓存的需求,就是在没有网络的情况下,以前可以打开的网页也可以通过缓存文件打开,主要代码为:

webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);webSettings.setAppCacheEnabled(true);String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/gefdemoweb";Log.e(null,path);webSettings.setAppCachePath(path);

第一行设置了缓存模式,第二行设置可以缓存,然后下面设置缓存路径,关于缓存模式有很多种:

public static final int LOAD_DEFAULT = -1;//默认模式,当缓存资源是可用的不过期,就使用,否次网络加载public static final int LOAD_NORMAL = 0;//This value is obsolete,过时了,不用管public static final int LOAD_CACHE_ELSE_NETWORK = 1;//当缓存资源是可用的就使用,即使它是过期的,否次网络加载public static final int LOAD_NO_CACHE = 2;//不使用缓存public static final int LOAD_CACHE_ONLY = 3;//不使用网络

然后说一下按返回键的问题,如果你不做任何设置,按返回键肯定要跳到上一个activity,但是我们想让他返回到上一个加载的网页怎么办:

@Overridepublic boolean onKeyDown(int keyCode, KeyEvent event) {    if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()){        webView.goBack();        return true;    }    return super.onKeyDown(keyCode, event);}

完美解决。

最后看一下webSetting的其它常用设置:
setJavaScriptEnabled(true); //支持js
setPluginsEnabled(true); //支持插件
setUseWideViewPort(false); //将图片调整到适合webview的大小
setSupportZoom(true); //支持缩放
setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN); //支持内容重新布局
supportMultipleWindows(); //多窗口
setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); //关闭webview中缓存
setAllowFileAccess(true); //设置可以访问文件
setNeedInitialFocus(true); //当webview调用requestFocus时为webview设置节点
webview webSettings.setBuiltInZoomControls(true); //设置支持缩放
setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
setLoadWithOverviewMode(true); // 缩放至屏幕的大小
setLoadsImagesAutomatically(true); //支持自动加载图片

0 0