WebView调用调用Java方法
- 允许WebView加载js
1 | webView.getSettings().setJavaScriptEnabled(true); |
- 编写js接口类
- 给webview添加js接口
1 | webView.addJavascriptInterface(obj,interfaceName); |
Android 调用js方法
使用loadUrl方法调用javascript
1 | //jsString是要调用的js代码的字符串 |
实例
新建一个工程WebViewDemo
layout_main.xml代码如下。分为上下两个部分,上部分为WebView,下部分为Native。两部分均有一个输入框和按钮,输入文字点击按钮,就会在对面的输入框显示。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<WebView
android:id="@+id/webview"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:orientation="vertical"
android:layout_weight="1">
<TextView
android:textColor="@android:color/black"
android:layout_marginLeft="10dp"
android:layout_marginTop="20dp"
android:textStyle="bold"
android:textSize="30dp"
android:text="Native"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<EditText
android:id="@+id/et"
android:layout_marginTop="20dp"
android:hint="请输入内容"
android:layout_width="match_parent"
android:layout_height="100px" />
<Button
android:id="@+id/send"
android:text="发送到WebView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>MainActivity实例化控件,并且允许WebView加载js
编写js接口类LbzJsInterface
1 | public class LbzJsInterface { |
1 | public interface JSBridge { |
- 给webview添加js接口
1 | webView.addJavascriptInterface(new LbzJsInterface(this), "lbzLauncher"); |
- MainActivity实现JSBridge
1 | @Override |
- WebView要加载index.html
1 | <!DOCTYPE html> |
- 加载html
1 | webView.loadUrl("file:///android_asset/index.html"); |
- 添加Native的监听事件,在监听中Android 调用js方法
1 | send.setOnClickListener(new View.OnClickListener() { |
- Demo的运行状态
