android webview用法大全
时间: 2023-10-30 21:08:42 浏览: 195
android webview的用法总结
以下是Android WebView的用法大全:
1. 在XML布局文件中添加WebView组件
```
<WebView
android:id="@+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
```
2. 在Java代码中获取WebView组件并设置WebViewClient
```
WebView webView = findViewById(R.id.webview);
webView.setWebViewClient(new WebViewClient());
```
3. 加载网页
```
webView.loadUrl("https://www.example.com");
```
4. 后退和前进
```
if(webView.canGoBack()) {
webView.goBack();
}
if(webView.canGoForward()) {
webView.goForward();
}
```
5. 加载本地HTML页面
```
webView.loadUrl("file:///android_asset/index.html");
```
6. 设置JavaScript支持
```
webView.getSettings().setJavaScriptEnabled(true);
```
7. 设置缩放
```
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setDisplayZoomControls(false);
```
8. 处理网页中的URL
```
webView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if(url.startsWith("mailto:")) {
Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse(url));
startActivity(intent);
return true;
}
view.loadUrl(url);
return true;
}
});
```
9. 拦截网页中的请求
```
webView.setWebViewClient(new WebViewClient() {
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
if(request.getUrl().toString().endsWith(".png")) {
try {
InputStream inputStream = getAssets().open("image.png");
return new WebResourceResponse("image/png", "UTF-8", inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
return super.shouldInterceptRequest(view, request);
}
});
```
10. 处理页面加载事件
```
webView.setWebViewClient(new WebViewClient() {
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
progressBar.setVisibility(View.VISIBLE);
}
@Override
public void onPageFinished(WebView view, String url) {
progressBar.setVisibility(View.GONE);
}
@Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
Toast.makeText(MainActivity.this, "Error: " + error.getDescription(), Toast.LENGTH_SHORT).show();
}
});
```
11. 调用JavaScript代码
```
webView.loadUrl("javascript:alert('Hello, world!')");
```
12. 与JavaScript交互
```
webView.addJavascriptInterface(new Object() {
@JavascriptInterface
public void showToast(String message) {
Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
}
}, "android");
```
以上是Android WebView的用法大全,希望能对你有所帮助。
阅读全文