安卓嵌套网页示例

注意配置网络访问权限

从Android 9.0(API级别28)开始,默认情况下禁用明文支持,因此http的url均无法在webview中加载

在application中添加

android:usesCleartextTraffic="true"

样式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
tools:context=".MainActivity">

<WebView
android:id="@+id/wv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="visible" />
</LinearLayout>

Activity

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package com.example.myqq;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView webView = (WebView)findViewById(R.id.wv);
String url = "https://xy-bz.github.io/";
//此方法可以在webview中打开链接而不会跳转到外部浏览器
webView.setWebViewClient(new WebViewClient());
//此方法可以启用html5页面的javascript
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(url);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);//设置js可以直接打开窗口,如window.open(),默认为false
webView.getSettings().setSupportZoom(true);//是否可以缩放,默认true
webView.getSettings().setBuiltInZoomControls(true);//是否显示缩放按钮,默认false
webView.getSettings().setLoadWithOverviewMode(true);//和setUseWideViewPort(true)一起解决网页自适应问题
webView.getSettings().setAppCacheEnabled(true);//是否使用缓存
webView.getSettings().setDomStorageEnabled(true);//DOM Storage
}
}

manifest

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myqq">
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<application
android:usesCleartextTraffic="true"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="myblog"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.AppCompat.NoActionBar">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

结果