应用场景
在应用程序里展示一些网页(套着app的外壳,内容是h5页面)
基于webView的混合开发,在Android原生app里,通过webView控件嵌入web页面
效果展示
涉及知识点
1、WebView和h5交互
2、WebView和js交互
代码应用
R.layout.activity_webview_test
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<data>
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<WebView
android:id="@+id/webview"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="调用js方法" />
</LinearLayout>
</layout>
html代码-本地文件
<html lang="zh-CN">
<p id='p'>hello world</p>
<a style="color: red;" onclick="location.href='mtd://forget_pwd'">重定向和scheme跳转button</a>
<script>
function test(){
document.getElementById("p").innerHTML += " 你好!"
}
</script>
<button onclick="justTest.hello('js调用安卓方法!')">调用安卓方法</button>
</html>
1、WebView和h5交互
协议监听(点击红字:重定向和scheme跳转button)
重定向:H5页面点击锚点,根据锚点具体跳转路径APP端跳转具体的页面
Activity
override fun initView() {
binding.webview.apply {
settings.javaScriptEnabled = true
loadUrl("file:///android_asset/show.html")
binding.webview.webViewClient = MyWebViewClient(context)
}
ac-通过WebViewClient复写shouldOverridUrlLoading()
/**
* shouldOverrideUrlLoading重定向
*/
private class MyWebViewClient(val context:Context) : WebViewClient() {
@SuppressWarnings("deprecation")
override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
if (url == "mtd://forget_pwd") {//协议
val intent = Intent()
intent.setClass(context, MainActivity::class.java)
context.startActivity(intent)//页面跳转
}
return true
}
}
2、WebView和js交互
Android原生调用js方法
override fun initView() {
binding.webview.apply {
settings.javaScriptEnabled = true//允许开启JavaScript
loadUrl("file:///android_asset/show.html")
}
binding.btn.setOnClickListener { testJs() }
}
/**
* Android调用Js方法
*/
private fun testJs() {
binding.webview.loadUrl("javascript:test()")
}
justTest相当于接口,有@JavascriptInterface注解的方法,就是可以在该接口下被js调用的方法
js调用Android原生方法
override fun initView() {
binding.webview.apply {
//开启JavaScript
settings.javaScriptEnabled = true
loadUrl("file:///android_asset/show.html")
}
//给webview绑定上JavaScript
binding.webview.addJavascriptInterface(this, "justTest")
}
/**
* 定义被js调用的Android原生方法
*/
@JavascriptInterface
fun hello(msg: String) {
toast(msg)
}
<html lang="zh-CN">
<p id='p'>hello world</p>
<script>
function test(){
document.getElementById("p").innerHTML += " 你好!"
}
</script>
<button onclick="justTest.hello('js调用安卓方法!')">调用安卓方法</button>
</html>
注解
@JavascriptInterface 注释的方法必须为public