To display progress when loading a URL in Android WebView, you can achieve this through the following steps:
- Create a progress bar: You can use the
ProgressBarwidget. - Set up the WebView client: Use
WebViewClientandWebChromeClientto listen for loading events. - Monitor the loading progress and update the progress bar: Update the progress bar's progress in the
onProgressChangedmethod ofWebChromeClient.
Here is a simple example:
First, you need to add a ProgressBar and a WebView in 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"> <ProgressBar android:id="@+id/progressBar" android:layout_width="match_parent" android:layout_height="4dp" style="@style/Widget.AppCompat.ProgressBar.Horizontal" /> <WebView android:id="@+id/webView" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@id/progressBar" /> </RelativeLayout>
Next, in your Activity or Fragment, configure the WebView and ProgressBar:
javapublic class MyActivity extends AppCompatActivity { private WebView webView; private ProgressBar progressBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_my); webView = findViewById(R.id.webView); progressBar = findViewById(R.id.progressBar); // Initialize WebView settings initWebView(); // Load URL webView.loadUrl("https://www.example.com"); } private void initWebView() { // Enable JavaScript webView.getSettings().setJavaScriptEnabled(true); // Set up WebView client webView.setWebViewClient(new WebViewClient() { @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); // Show progress bar when page starts loading progressBar.setVisibility(View.VISIBLE); } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); // Hide progress bar when page finishes loading progressBar.setVisibility(View.GONE); } }); // Set WebChromeClient to track loading progress webView.setWebChromeClient(new WebChromeClient() { @Override public void onProgressChanged(WebView view, int newProgress) { // Update progress bar's progress progressBar.setProgress(newProgress); if (newProgress == 100) { // Page loading complete progressBar.setVisibility(View.GONE); } } }); } }
In this example, when the URL starts loading, the progress bar appears and updates as the page loads. When the page finishes loading, the progress bar automatically hides.
This covers the basic steps and example code for displaying a progress bar when loading a URL in Android WebView. In actual projects, you may need to adjust and optimize this code based on specific requirements.
2024年6月29日 12:07 回复