Android与WebView的js交互

82 阅读1分钟

参考资料(慕课网《Android与WebView的js交互》)

1.WebView的使用场景

首先是类似慕课网客户端的这样一个意见反馈的页面,就是用WebView实现的,

另外的是许多app的用户协议这一页面,这样的文字排版呢,则使用HTML实现会比较方便,

然后是很多Android客户端的新闻页或者广告页面,

它们都是用WebView来实现的;

2.Android与WebView的交互

下面说一下两个最常见的例子:

2.1.首先是,通过WebView调用Java方法

首先呢我们可以看到下图新闻页中其中间有一个视频,当我们去点击视频的播放按钮的时候,他会启动一个fragment并播放这段视频流;

2.2.接下来是Android客户端调用WebView的js方法

我们可以看到左边这个新闻它初始的背景是白色的,

当我们去点击“夜间模式”按钮的时候,

它会将WebView 的背景变为黑色;

##3.Demo详解 WebView调用Java方法

1. 允许WebView加载js:
webView.getSettings().setJavaScriptEnabled(true);


2. 编写js接口类;


3. 给WebView添加js接口

WebView.addJavascriptInterface(obj,name);


下面新建一个项目,我们来做一个Demo,首先是main布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <WebView
        android:id="@+id/webview"
        android:layout_width="match_parent"
        android:layout_height="280dp"/>

    <TextView
        android:id="@+id/tv_result"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="#0e00cc"
        android:textSize="20sp"
        android:layout_marginTop="20dp"
        tools:text="12345"/>

</LinearLayout>

使用tools:text跟使用android:text的区别就是使用tools:text的时候,text的内容只在布局预览中存在,而在真正运行的时候是不存在的; Textview里边使用android:layout_marginTop="20dp",让其与WebView保持距离。