Android ProgessBar while loading WebView

后端 未结 12 2568
闹比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:48

    I want to show a progressBar while the webView gets loaded and hide the progessBar when the webView gets loaded completely.

    Following snippet will help you.

    main.xml

    
    
        
    
    

    Main.class

    public class Main extends Activity {
        private WebView webview;
        private static final String TAG = "Main";
        private ProgressDialog progressBar;
    
        /** Called when the activity is first created. */@Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            requestWindowFeature(Window.FEATURE_NO_TITLE);
    
            setContentView(R.layout.main);
    
            this.webview = (WebView) findViewById(R.id.webview);
    
            WebSettings settings = webview.getSettings();
            settings.setJavaScriptEnabled(true);
            webview.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
    
            final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
    
            progressBar = ProgressDialog.show(Main.this, "Showing ProgressDialog", "Loading...");
    
            webview.setWebViewClient(new WebViewClient() {
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    Log.i(TAG, "Processing webview url click...");
                    view.loadUrl(url);
                    return true;
                }
    
                public void onPageFinished(WebView view, String url) {
                    Log.i(TAG, "Finished loading URL: " + url);
                    if (progressBar.isShowing()) {
                        progressBar.dismiss();
                    }
                }
    
                public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                    Log.e(TAG, "Error: " + description);
                    Toast.makeText(Main.this, "Oh no! " + description, Toast.LENGTH_SHORT).show();
                    alertDialog.setTitle("Error");
                    alertDialog.setMessage(description);
                    alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            return;
                        }
                    });
                    alertDialog.show();
                }
            });
            webview.loadUrl("http://www.google.com");
        }
    }
    

提交回复
热议问题