首先添加网络权限
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
其中还得添加
<application
android:usesCleartextTraffic="true"
</application>
不然网页无法加载
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.webviewdemo.WebViewActivity"
>
<WebView
android:id="@+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
</WebView>
</LinearLayout>
package com.example.webviewdemo;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Environment;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class WebViewActivity extends AppCompatActivity {
private WebView mwebView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_view);
mwebView = findViewById(R.id.webview);
mwebView.loadUrl("http://www.baidu.com/");
// mwebView.loadUrl("file://" + Environment.getExternalStorageDirectory().getPath() +"/1/index.html");
mwebView.setWebViewClient(new WebViewClient());
}
}
|