乐闻世界logo
搜索文章和话题

How to display a progress bar when WebView loads a URL, in Android ?

1个答案

1

Using WebView to load web pages in Android is a common practice, and displaying a progress bar is an excellent way to enhance user experience by providing users with feedback on the approximate loading progress. I will now provide a detailed explanation of how to integrate a progress bar within WebView.

First, you need to add WebView and ProgressBar controls to your layout file. For example:

xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <WebView android:id="@+id/webview" android:layout_width="match_parent" android:layout_height="match_parent"/> <ProgressBar android:id="@+id/progressbar" android:layout_width="match_parent" android:layout_height="4dp" android:layout_alignParentTop="true" android:indeterminate="false" android:max="100"/> </RelativeLayout>

Next, in your Activity or Fragment's Java/Kotlin code, you need to set up WebView's WebViewClient and WebChromeClient. The primary task is to listen for progress changes within WebChromeClient and update the ProgressBar's progress.

Here is a Java implementation example:

java
public class WebViewActivity extends AppCompatActivity { private WebView webView; private ProgressBar progressBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_web_view); webView = findViewById(R.id.webview); progressBar = findViewById(R.id.progressbar); webView.getSettings().setJavaScriptEnabled(true); webView.setWebChromeClient(new WebChromeClient() { @Override public void onProgressChanged(WebView view, int newProgress) { super.onProgressChanged(view, newProgress); progressBar.setProgress(newProgress); if (newProgress == 100) { progressBar.setVisibility(View.GONE); } else { progressBar.setVisibility(View.VISIBLE); } } }); webView.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } }); webView.loadUrl("https://www.example.com"); } }

In this code snippet, we first set up a new WebChromeClient object using the setWebChromeClient method and override the onProgressChanged method. This method is called whenever the page loading progress changes, and we update the ProgressBar's progress using the setProgress method. When the page loading is complete (i.e., the progress reaches 100%), we hide the ProgressBar by setting setVisibility(View.GONE).

This implementation is straightforward and effectively provides users with feedback on the loading progress.

2024年8月8日 14:12 回复

你的答案