object WebViewManager {

fun getWebUrl(name: String): String {

return “file:///android_asset/www/${name}.html”

}

}

三 WebView处理


3.1 页面中添加WebView

<?xml version="1.0" encoding="utf-8"?>

<androidx.constraintlayout.widget.ConstraintLayout 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">

<WebView

android:id="@+id/webview"

android:layout_width=“match_parent”

android:layout_height=“match_parent” />

</androidx.constraintlayout.widget.ConstraintLayout>

3.2 初始化WebView,并加载Url

webView = findViewById(R.id.webview)

var url = WebViewManager.getWebUrl(“index”);

webView.loadUrl(url);

3.3 启用 JavaScript

JavaScript 在 WebView 中默认处于停用状态。您可以通过附加到 WebViewWebSettings 启用 JavaScript。您也可以使用 getSettings() 检索 WebSettings,然后使用 setJavaScriptEnabled() 启用 JavaScript

webView.settings.javaScriptEnabled = true

四 android和WebView相互调用


4.1 JavascriptInterface回调类为当前Activity

4.1.1 WebView的addJavascriptInterface中Object为当前Activity

webView.addJavascrip

《Android学习笔记总结+最新移动架构视频+大厂安卓面试真题+项目实战源码讲义》

浏览器打开:qq.cn.hn/FTe 免费领取

tInterface(this, “Android”)

  • this:代表当前Activity

  • “Android”:是固定写法

4.1.2 当前Activity中实现js中定义的方法

/**

  • @description:android调用js无参函数

*/

@JavascriptInterface

fun androidCallJs() {

Toast.makeText(this, “androidCallJs”, Toast.LENGTH_LONG).show()

}

/**

  • @description:android调用js带参函数

*/

@JavascriptInterface

fun androidCallJsWithArgs(name: String) {

Toast.makeText(this, “androidCallJsWithArgs:$name”, Toast.LENGTH_LONG).show()

}

/**

  • @description:js调用android无参函数

*/

@JavascriptInterface

fun jsCallAndroid(): String {

return “jsCallAndroid”

}

/**

  • @description:js调用android带参函数

*/

@JavascriptInterface

fun jsCallAndroidWithArgs(name: String): String {

return “jsCallAndroidWithArgs=$name”

}

4.1.3 JS中相应的方法调用Android.JavascriptInterface对应的方法

function androidCallJs() {

Android.androidCallJs();

}

点击JS中的第一个按钮,调用androidCallJs();方法,执行Android.androidCallJs();,会回调android Activity中相应的androidCallJs()方法

4.2 将JS中的方法放到单独的类中实现(WebAppInterface)

4.2.1 定义WebAppInterface

class WebAppInterface(private val mContext: Context) {

/**

  • @description:android调用js无参函数

*/

@JavascriptInterface

fun androidCallJs() {

Toast.makeText(mContext, “androidCallJs”, Toast.LENGTH_LONG).show()

}

/**

  • @description:android调用js带参函数

*/

@JavascriptInterface

fun androidCallJsWithArgs(name: String) {

Toast.makeText(mContext, “androidCallJsWithArgs:$name”, Toast.LENGTH_LONG).show()

}

/**

  • @description:js调用android无参函数

*/

@JavascriptInterface

Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐