1. 创建 WebView 和设置 WebView 设置
在 XML 布局中添加 WebView
在activity_main.xml里创建一个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/web_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
在 Activity 中配置 WebView
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Bundle;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private WebView webView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = findViewById(R.id.web_view);
// 设置 WebView 的设置
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true); // 启用 JavaScript
// 加载本地 HTML 或 URL
webView.loadUrl("file:///android_asset/index.html");
// 设置 WebView 客户端
webView.setWebViewClient(new WebViewClient());
// 注册 JavaScript 接口
webView.addJavascriptInterface(new MyJavaScriptInterface(), "AndroidInterface");
}
// 创建 JavaScript 接口类
public class MyJavaScriptInterface {
@JavascriptInterface
public void showToast(String message) {
// 调用 Android 原生方法(例如显示 Toast)
Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
}
}
}
2. 创建 HTML 页面,调用 JavaScript 接口
接下来,需要在 WebView 加载的 HTML 页面中通过 JavaScript 调用 AndroidInterface
接口。
先创建assets目录,在Project视角下,选中src/main, 右键单击New,选择Directory,最后选中assets即可。
在 assets
文件夹中创建 index.html
文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebView Example</title>
</head>
<body>
<h1>WebView with JavaScript Interface</h1>
<button onclick="callAndroidMethod()">Call Android Method</button>
<script type="text/javascript">
function callAndroidMethod() {
// 调用 Android 原生方法
AndroidInterface.showToast("Hello from JavaScript!");
}
</script>
</body>
</html>
3. 权限和配置
确保在 AndroidManifest.xml 中添加了对 INTERNET
权限的声明(如果加载的是外部 URL):
<uses-permission android:name="android.permission.INTERNET" />
4. 运行示例
- 点击 HTML 页面中的按钮时,
callAndroidMethod()
会调用AndroidInterface.showToast()
方法。 - 这个方法会触发
MainActivity
中的showToast
方法,从而显示一个Toast
消息。