WebView的简单介绍和简答使用
WebView
Webview的概念:
WebView 是一个用来显示网页的控件,和使用系统其他控件没什么区别, WeView 是微型浏览器。它包含一个浏览器该有的基本功能,例如:前进、后退下一页、搜索、和网页互相调用等功能。
为什么学习Webview????
最大的优势是迭代方便, 只需要修改服务端网页的代码,Android应用就会同步更新。
WebView的缺点:
没有原生控件流畅,用户体验相对较差。
一,WebView使用步骤:
1、添加网络权限
2、在 应用文件的Layout中添加一个控件WebView:
3、在 Activity 拿到实例化WebView 控件:
WebView webView = (WebView) findViewById(R.id.webview);
4、使用 WebView 加载网页
//加载网页链接
webView.loadUrl(“http://keithxiaoy.com”);
//加载本地assets目录下的网页
webView.loadUrl(“file:///android_asset/keithxiaoy.html”);
//加载手机本地的html页面
wwebView.loadUrl(“file:///sdcard /taobao.html”)
三,WebView 中网页的前进, 后退, 停止,刷新:
回退:先检查是否可以回退
webView.canGoBack();//是否可以跳到上一页(如果返回false,说明已经是第一页)
webView.goBack();//跳到上个页面 一般用在onBackPressed()函数中。
前进,检查是否可以前进:
webView.canGoForward();//是否可以跳到下一页(如果返回false,说明已经是最后一页)
webView.goForward();//跳到下个页面
停止:
webView.stopLoading();
刷新:
webView.reload();
四,Webview辅助类
WebSettings
设置WebView的一些属性。例如允许Android与js互调,允许使用缓存,允许使用内置的缩放组件等。
WebSettings webSettings = mWebView.getSettings();//获取websSetting。
webSettings.setJavaScriptEnabled(true); // 支持Js调用原生。
// 开启DOM缓存,默认状态下是不支持LocalStorage的 webSettings.setDomStorageEnabled(true); // 开启数据库缓存 webSettings.setDatabaseEnabled(true); // 支持自动加载图片
webSettings.setCacheMode(WebSettings.LOAD_DEFAULT); // 支持启用缓存模式。
…
WebViewClient
WebViewClient主要用来处理请求事件和在合适的时候回调进行一些逻辑处理。
onPageStarted(WebView view, String url, Bitmap favicon):WebView 开始加载页面时回调,一次Frame加载对应一次回调。
onLoadResource(WebView view, String url):WebView 加载页面资源时会回调,每一个资源产生的一次网络加载,除非本地有当前 url 对应有缓存,否则就会加载。
shouldInterceptRequest(WebView view, String url):WebView 可以拦截某一次的 request 来返回我们自己加载的数据,这个方法在后面缓存会有很大作用。
shouldInterceptRequest(WebView view, android.webkit.WebResourceRequest request):WebView 可以拦截某一次的 request 来返回我们自己加载的数据,这个方法在后面缓存会有很大作用。
shouldOverrideUrlLoading(WebView view, String url):是否在 WebView 内加载页面。
onReceivedSslError(WebView view, SslErrorHandler handler, SslError error):WebView ssl 访问证书出错,handler.cancel()取消加载,handler.proceed()对然错误也继续加载。
onPageFinished(WebView view, String url):WebView 完成加载页面时回调,一次Frame加载对应一次回调。
onReceivedError(WebView view, int errorCode, String description, String failingUrl):WebView 访问 url 出错。
WebChromeClient
辅助WebView处理Javascript的对话框、网站图标、网站Title、加载进度,实现更好的展示效果等。
Android与Js如何交互?
①android如何调用js。
调用形式:
1,websetting.setJavaScriptEnable(true) 让android和js可以互相调用。
2, mWebView.loadUrl(“javascript:wave()”);
其中wave()是js中的一个方法。
②js如何调用android。
1,websetting.setJavaScriptEnable(true) 让android和js可以互相调用。
2,实现一个Java类,类中方法使用注解@JavascriptInterface。
3、使用系统webview方法 addJavascriptInterface 注入 java 对象来让js调用我们注解的方法。
4,在js中就可以调用Java类注解的方法。
代码中的“demo”是在android中指定的调用名称,即
mWebView.addJavascriptInterface(new DemoJavaScriptInterface(), “demo”);
调用形式:
代码中的clickOnAndroid()是“demo”对应的对象:new DemoJavaScriptInterface() 中的一个方法。
package com.example.webview;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.btn_loading).setOnClickListener(this);
findViewById(R.id.btn_fromJs).setOnClickListener(this);
}
@Override
public void onClick(View v) {
Intent intent=new Intent();
switch (v.getId()){
case R.id.btn_loading:
intent.setClass(this,LoadingActivity.class);
break;
case R.id.btn_fromJs:
intent.setClass(this,JsActivity.class);
break;
default:
break;
}
startActivity(intent);
}
}
package com.example.webview;
import android.graphics.Bitmap;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
public class LoadingActivity extends AppCompatActivity implements View.OnClickListener {
private String url="https://tech.meituan.com/WebViewPerf.html";
private ProgressBar pb;
private WebView web;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_loading);
initview();
initwebview();
}
private void initwebview() {
web.loadUrl(url);
web.setWebViewClient(new WebViewClient(){
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
pb.setVisibility(View.VISIBLE);
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
pb.setVisibility(View.GONE);
}
});
web.setWebChromeClient(new WebChromeClient(){
@Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
pb.setProgress(newProgress);
}
});
}
private void initview() {
findViewById(R.id.go).setOnClickListener(this);
findViewById(R.id.back).setOnClickListener(this);
findViewById(R.id.refresn).setOnClickListener(this);
findViewById(R.id.stop).setOnClickListener(this);
pb=findViewById(R.id.prb);
web=findViewById(R.id.wb);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.go:
//如果可以前进就前进
if(web.canGoForward()){
web.goForward();
}
break;
case R.id.back:
if(web.canGoBack()){
web.goBack();
}
break;
case R.id.refresn:
web.reload();
break;
case R.id.stop:
web.stopLoading();
break;
default:
break;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
web.destroy();
}
}
package com.example.webview;
import android.content.Context;
import android.webkit.JavascriptInterface;
import android.widget.Toast;
public class JSInterface {
private Context context;
public JSInterface(Context context) {
this.context = context;
}
@JavascriptInterface
public void noParameterFunction(){
Toast.makeText(context, "JS调用安卓", Toast.LENGTH_SHORT).show();
}
@JavascriptInterface
public void parameterFunction(String s){
Toast.makeText(context, "JS调用安卓有参成功"+s, Toast.LENGTH_SHORT).show();
}
}
package com.example.webview;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import java.io.IOException;
public class JsActivity extends AppCompatActivity implements View.OnClickListener {
private WebView web;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_js);
web = findViewById(R.id.webeb);
findViewById(R.id.btn_Jsto).setOnClickListener(this);
findViewById(R.id.btn_toJs).setOnClickListener(this);
initwebview();
}
private void initwebview() {
web.loadUrl("file:///android_asset/js.html");
WebSettings settings = web.getSettings();
settings.setJavaScriptEnabled(true);
web.addJavascriptInterface(new JSInterface(this), "android");
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_Jsto:
web.loadUrl("javascript:callJsWithArg(\"我是安卓端过来的\")");
break;
case R.id.btn_toJs:
break;
default:
break;
}
}
}
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript">
function callAlert() {
alert("Android Alert");
}
function callJs(){
document.getElementById("content").innerHTML =
"<br\>Android调用了JS的无参函数";
}
function callJsWithArg(arg){
document.getElementById("content").innerHTML =
"<br\>Android调用了JS的有参函数 " + arg;
}
</script>
</head>
<body>
以下为html内容<br/>
<h1><div id="content">显示一条文本</div></h1>
<br/>
<input type="button" value="调用Android代码,且无参" onclick="window.android.noParameterFunction()" />
<br/>
<input type="button" value="调用Android代码,且有参" onclick="window.android.parameterFunction('JS->android 有参成功')"/>
</body>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<Button
android:text="加载网页"
android:id="@+id/btn_loading"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:text="调用JS"
android:id="@+id/btn_fromJs"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".JsActivity"
android:orientation="vertical">
<Button
android:text="安卓调用JS"
android:id="@+id/btn_toJs"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:text="JS调用安卓"
android:id="@+id/btn_Jsto"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<WebView
android:id="@+id/webeb"
android:layout_width="match_parent"
android:layout_height="match_parent"></WebView>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".LoadingActivity"
android:orientation="vertical">
<LinearLayout
android:orientation="horizontal"
android:weightSum="4"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="@+id/go"
android:text="前进"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
/>
<Button
android:id="@+id/back"
android:text="后退"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
/>
<Button
android:id="@+id/refresn"
android:text="刷新"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
/>
<Button
android:id="@+id/stop"
android:text="暂停"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
/>
</LinearLayout>
<ProgressBar
style="@style/Widget.AppCompat.ProgressBar.Horizontal"
android:id="@+id/prb"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<WebView
android:id="@+id/wb"
android:layout_width="match_parent"
android:layout_height="match_parent"></WebView>
</LinearLayout>