效果图
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/9c385e15a0c104f46d973436a515e00d.gif)
xml文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ProgressBar
android:layout_width="match_parent"
android:layout_height="3dp"
style="@style/Widget.AppCompat.ProgressBar.Horizontal"
android:progress="0"
android:id="@+id/pb1"/>
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/wv"/>
</LinearLayout>
java 文件
package com.dai.hellworld;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
public class WebViewActivity extends AppCompatActivity {
private WebView wv;
private ProgressBar bar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_view);
wv = findViewById(R.id.wv);
bar = findViewById(R.id.pb1);
wv.loadUrl("https://m.baidu.com");
wv.getSettings().setJavaScriptEnabled(true);
wv.setWebViewClient(new MyViewClient());
wv.setWebChromeClient(new MyChromeClient());
}
class MyViewClient extends WebViewClient {
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
view.loadUrl(request.getUrl().toString());
return super.shouldOverrideUrlLoading(view, request);
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
bar.setProgress(0);
super.onPageStarted(view, url, favicon);
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
bar.setProgress(100);
}
}
class MyChromeClient extends WebChromeClient {
@Override
public void onProgressChanged(WebView view, int newProgress) {
if (bar.getProgress() == 100) {
bar.setVisibility(View.GONE);
} else {
bar.setProgress(newProgress);
}
super.onProgressChanged(view, newProgress);
}
@Override
public void onReceivedTitle(WebView view, String title) {
super.onReceivedTitle(view, view.getTitle());
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && wv.canGoBack()) {
wv.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}