WebView就是嵌入在Android UI中的浏览器,在应用中,难免要进行JS与本地的交互,下面记录了大致的实现流程。
1、实现MainActivity的布局
<?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"
android:background="@color/white">
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="本地调用js中的方法"/>
<WebView
android:id="@+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent">
</WebView>
</LinearLayout>
2、在android工程的main目录下,新建一个assets文件夹,并在这个文件夹下创建一个test.html文件
<html>
<body>
<br><br>
<h3>这是WebView界面</h3>
<script>
// js的方法
function funFromjs(){
document.getElementById("helloweb").innerHTML="Hello WebView,I'm from js";
// 本地的方法
myObj.fun1FromAndroid("调用android本地方法fun1FromAndroid(String name)!!");
}
</script>
<p></p>
<div id="helloweb">
</div>
</body>
</html>
3、在MainActivity中进行交互的实现
1)初始化View
WebView mWebView;
Button mBtn1;
mWebView = (WebView) findViewById(R.id.webView);
mBtn1 = (Button) findViewById(R.id.button);
2)实现JS与本地交互
//设置编码
mWebView.getSettings().setDefaultTextEncodingName("utf-8");
//支持js
mWebView.getSettings().setJavaScriptEnabled(true);
//设置本地调用对象及其接口
mWebView.addJavascriptInterface(new JavaScriptObject(getApplicationContext()), "myObj");
//载入js
String url = "file:///android_asset/test.html";
mWebView.loadUrl(url);
//点击调用js中方法
mBtn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 调用js的方法
mWebView.loadUrl("javascript:funFromjs()");
}
});
3)在MainActivity中声明本地对象
public class JavaScriptObject {
Context mContext;
public JavaScriptObject(Context mContxt) {
this.mContext = mContxt;
}
@JavascriptInterface
public void fun1FromAndroid(String name) {
Toast.makeText(mContext, name, Toast.LENGTH_LONG).show();
}
}
注意:
在本地方法上必须进行依赖注入@JavascriptInterface,否则在js中调用本地方法无效。
3、最后的效果如下所示
点击按钮,本地会调用JS的funFromjs()方法,在WebView中显示 Hello WebView,I'm from js
同时,调用了本地方法fun1FromAndroid(String name),Toast显示 调用android本地方法fun1FromAndroid(String name)!!
WebView加载不同来源的网页
//打开本包内assets目录下的index.html文件
mWebView.loadUrl(" file:///android_asset/index.html ");
//打开本地sd卡内的index.html文件
mWebView.loadUrl("content://com.android.htmlfileprovider/sdcard/index.html");
//打开指定URL的html文件
mWebView.loadUrl(" http://m.oschina.net");