Search code examples
javaandroidandroid-webviewandroid-9.0-pie

Why is the progress bar in a webview displayed with a delay in Android 9.0?


I'm a newbie to Android and I'm developing an app which contains fragments. One of the fragments contains a WebView. I'm using a ProgressBar as it is mentioned in many tutorials for webviews so that there is a loading animation when the page loads.

The problem is, when I run the app and load a page in WebView (no matter if external device or emulator) the progress bar appears with a small delay (approx. 2 seconds) and not directly after pressing a link for example. Only shortly before the new page starts to load, it appears briefly and disappears again as desired when the page is loaded.

I've tested several android versions and It works fine on all of them except for Android 9.0

Here is my WebViewClient class that I'm using for my webView:

private class MyWebviewClient extends WebViewClient {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            webProgress.setVisibility(View.VISIBLE);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            webProgress.setVisibility(View.GONE);
        }

    }

And here is my xml layout file:

<?xml version="1.0" encoding="utf-8"?>
<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"
        style="?android:attr/progressBarStyle"
        android:layout_centerInParent="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />


</RelativeLayout>

I just can't figure out what I'm doing wrong.


Solution

  • I found the answer myself. I had to overwrite shouldOverrideUrlLoading() instead of onPageStarted() so that the ProgressBar is displayed immediately after clicking a link and not later.

    private class MyWebviewClient extends WebViewClient {
    
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                webProgress.setVisibility(View.VISIBLE);
                return super.shouldOverrideUrlLoading(view, url);
        }
    
            @Override
            public void onPageFinished(WebView view, String url) {
                webProgress.setVisibility(View.GONE);
            }
    
    }