WebView可以使得网页轻松的内嵌到app里,还可以直接跟js相互调用。
webview有两个方法:setWebChromeClient 和 setWebClient
setWebClient:主要处理解析,渲染网页等浏览器做的事情
setWebChromeClient:辅助WebView处理Javascript的对话框,网站图标,网站title,加载进度等
WebViewClient就是帮助WebView处理各种通知、请求事件的。
使用WebView:可以在代码中和布局中使用。
代码中:创建WebView的实例加入到Activity view tree中
WebView webview = new WebView(this);
setContentView(webview);
布局中:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:id="@+id/wv_shop"
android:layout_width="match_parent"
android:layout_height="match_parent">
</WebView>
</LinearLayout>
对WebView的设置
wvShop.loadUrl("http://demo3.tp-shop.cn");
WebSettings webSettings = wvShop.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setSupportZoom(true);
wvShop.setWebViewClient(mWebViewClientBase);
wvShop.setWebChromeClient(mWebChromeClientBase);
private WebViewClientBase mWebViewClientBase = new WebViewClientBase();
private class WebViewClientBase extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
}
@Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
}
@Override
public void doUpdateVisitedHistory(WebView view, String url,
boolean isReload) {
super.doUpdateVisitedHistory(view, url, isReload);
}
}
private WebChromeClientBase mWebChromeClientBase = new WebChromeClientBase();
private class WebChromeClientBase extends WebChromeClient {
@Override
public void onProgressChanged(WebView view, int newProgress) {
TpShopActivity.this.setProgress(newProgress * 1000);
}
@Override
public void onReceivedTitle(WebView view, String title) {
super.onReceivedTitle(view, title);
}
@Override
public void onReceivedTouchIconUrl(WebView view, String url,
boolean precomposed) {
super.onReceivedTouchIconUrl(view, url, precomposed);
}
@Override
public boolean onCreateWindow(WebView view, boolean isDialog,
boolean isUserGesture, Message resultMsg) {
return super.onCreateWindow(view, isDialog, isUserGesture, resultMsg);
}
}
对返回键的处理:
@Override
public void onBackPressed() {
// super.onBackPressed();
if (wvShop.canGoBack()){
wvShop.goBack();
}else{
finish();
}
}
参考文章:1.http://blog.youkuaiyun.com/yaodong379/article/details/51960451 使用方法详细。
2.http://blog.youkuaiyun.com/typename/article/details/39030091 有对webview方法的介绍。
3.http://zouhuajian01.blog.163.com/blog/static/117698772012111511449668/ 关于WebView的缩放