Search code examples
androidwebviewprogress-barloaddata

Android: How can i show progress bar while loading data into WebView?


How can I show the progress bar while loading data into my webview? My code :

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    this.requestWindowFeature(Window.FEATURE_PROGRESS);
    getWindow().setFeatureInt( Window.FEATURE_PROGRESS, Window.PROGRESS_VISIBILITY_ON); 
    this.setProgressBarVisibility(true);
    setContentView(R.layout.layout_article);
    WebView webview = (WebView) findViewById(R.id.webView);
    final Activity activity = this;
    webview.setWebChromeClient(new WebChromeClient() {
        public void onProgressChanged(WebView view, int progress) {
            activity.setProgress(progress * 100);
        }
    });

    webView.loadUrl("http://google.com");
}

Solution

  • public class MainActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            final ProgressBar progress = (ProgressBar) findViewById(R.id.progress);
    
            WebView webView = (WebView) findViewById(R.id.webview);
            webView.getSettings().setJavaScriptEnabled(true);
            webView.setWebViewClient(new WebViewClient() {
                @Override
                public boolean shouldOverrideUrlLoading(final WebView view, final String url) {
                    return false;
                }
    
                @Override
                public void onPageStarted(final WebView view, final String url, final Bitmap favicon) {
                    progress.setVisibility(View.VISIBLE);
                    super.onPageStarted(view, url, favicon);
                }
    
                @Override
                public void onPageFinished(final WebView view, final String url) {
                    progress.setVisibility(View.GONE);
                    super.onPageFinished(view, url);
                }
            });
    
            webView.loadUrl("http://google.com");
        }
    }
    

    And R.layout.activity_main:

    <?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/progress"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:visibility="gone"
            android:layout_centerInParent="true"/>
    </RelativeLayout>