Android ProgessBar while loading WebView

后端 未结 12 2598
闹比i
闹比i 2020-12-08 01:52

In my application, I have a WebView which loads any URL from the internet. Now, sometimes due to slow networks the page takes a long time to load and the user s

12条回答
  •  误落风尘
    2020-12-08 02:37

    if you want to show the progressbar every time the user loads page (and not only the first load), then you can use this:

    MainActivity.java

    public class MainActivity extends Activity
    {
        private WebView webView;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            webView = (WebView) findViewById(R.id.webView);
    
            final ProgressDialog progressBar = new ProgressDialog(MainActivity.this);
            progressBar.setMessage("Please wait...");
    
            webView.loadUrl("https://example.org/");
            webView.setWebViewClient(new WebViewClient() {
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    view.loadUrl(url);
                    return true;
                }
    
                @Override
                public void onPageStarted(WebView view, String url, Bitmap favicon) {
                    super.onPageStarted(view, url, favicon);
                    if (!progressBar.isShowing()) {
                        progressBar.show();
                    }
                }
    
                public void onPageFinished(WebView view, String url) {
                    if (progressBar.isShowing()) {
                        progressBar.dismiss();
                    }
                }
    
                public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                    if (progressBar.isShowing()) {
                        progressBar.dismiss();
                    }
                }
            });
    
        }
    }
    

    activity_main.xml :

    
    
    
        
    
    
    

提交回复
热议问题