Android开发之——Android和WebView相互调用,移动开发工程师的发展路线
object WebViewManager {
fun getWebUrl(name: String): String {
return “file:///android_asset/www/${name}.html”
}
}
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 中默认处于停用状态。您可以通过附加到 WebView 的 WebSettings 启用 JavaScript。您也可以使用 getSettings() 检索 WebSettings,然后使用 setJavaScriptEnabled() 启用 JavaScript
webView.settings.javaScriptEnabled = true
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
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)