加载 WebView 时的 Android ProgressBar

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11241513/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 06:28:22  来源:igfitidea点击:

Android ProgessBar while loading WebView

androidandroid-asynctaskandroid-webviewandroid-progressbar

提问by Swayam

In my application, I have a WebViewwhich loads any URL from the internet. Now, sometimes due to slow networks the page takes a long time to load and the user sees only a blank screen.

在我的应用程序中,我有一个WebView可以从 Internet 加载任何 URL。现在,有时由于网络缓慢,页面需要很长时间才能加载,用户只能看到一个空白屏幕。

I want to show a ProgressBarwhile the WebViewgets loaded and hide the ProgessBarwhen the WebViewgets loaded completely.

我想显示一段ProgressBar时间已WebView加载并隐藏ProgessBar何时WebView完全加载。

I know how to use the ProgressBarand AsyncTasks, but here is my problem.

我知道如何使用ProgressBarand AsyncTasks,但这是我的问题。

This is the code that I use to load my WebView.

这是我用来加载我的WebView.

    mWebView = (WebView) findViewById(R.id.webview);
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.setWebViewClient(new HelloWebViewClient());
    mWebView.loadUrl(web_URL);

And this my custom WebViewClientclass

这是我的自定义WebViewClient课程

private class HelloWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }
}

Now, if I try to show the ProgressBarusing AsyncTasksthen I guess I would have to give the code to load the URL in the doInBackGround()function of my AsyncTaskand show the progress through the onProgressUpdate()function.

现在,如果我尝试显示ProgressBarusing AsyncTasks那么我想我将不得不提供代码以在doInBackGround()my的函数中加载 URLAsyncTask并通过该onProgressUpdate()函数显示进度。

But, how do I load the URL inside the doInBackground() as doInBackground()runs on the Non-UI threadand I wont be able to use mWebView.loadUrl(web_URL)inside it.

但是,如何在 doInBackground() 中加载 URL,因为doInBackground()非 UI 线程上运行,而我将无法在其中使用mWebView.loadUrl(web_URL)

Any suggestions? Am I missing something obvious? Please guide me.

有什么建议?我错过了一些明显的东西吗?请指导我。

回答by Md Abdul Gafur

Check the source code. Help you and solve your problem...

检查源代码。帮助您解决您的问题...

public class AppWebViewClients extends WebViewClient {
     private ProgressBar progressBar;

    public AppWebViewClients(ProgressBar progressBar) {
        this.progressBar=progressBar;
        progressBar.setVisibility(View.VISIBLE);
    }
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        // TODO Auto-generated method stub
        view.loadUrl(url);
        return true;
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        // TODO Auto-generated method stub
        super.onPageFinished(view, url);
        progressBar.setVisibility(View.GONE);
    }
}

I think it help you.

我认为对你有帮助。

Thanks.

谢谢。

回答by Vipul Shah

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

我想在 webView 加载时显示一个 progressBar 并在 webView 完全加载时隐藏 progessBar。

Following snippet will help you.

以下代码段将对您有所帮助。

main.xml

主文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <WebView android:id="@+id/webview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1" />
</LinearLayout>

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");
    }
}

回答by Ishant Garg

pass your url in this method

在此方法中传递您的网址

private void startWebView(String url) {

            WebSettings settings = webView.getSettings();

            settings.setJavaScriptEnabled(true);
            webView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);

            webView.getSettings().setBuiltInZoomControls(true);
            webView.getSettings().setUseWideViewPort(true);
            webView.getSettings().setLoadWithOverviewMode(true);

            progressDialog = new ProgressDialog(ContestActivity.this);
            progressDialog.setMessage("Loading...");
            progressDialog.show();

            webView.setWebViewClient(new WebViewClient() {
                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    view.loadUrl(url);
                    return true;
                }

                @Override
                public void onPageFinished(WebView view, String url) {
                    if (progressDialog.isShowing()) {
                        progressDialog.dismiss();
                    }
                }

                @Override
                public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                    Toast.makeText(ContestActivity.this, "Error:" + description, Toast.LENGTH_SHORT).show();

                }
            });
            webView.loadUrl(url);
        }

回答by medskill

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

主活动.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 :

活动_main.xml :

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="0dp"
    android:paddingLeft="0dp"
    android:paddingRight="0dp"
    android:paddingTop="0dp"
    tools:showIn="@layout/activity_main">

    <WebView
        android:id="@+id/webView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true" />

</RelativeLayout>

回答by CoolMind

String url = "https://stackoverflow.com/questions/11241513/android-progessbar-while-loading-webview";
setProgressBarVisibility(View.VISIBLE);

webView.setWebViewClient(new WebViewClient() {
    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        super.onPageStarted(view, url, favicon);
        setProgressBarVisibility(View.VISIBLE);
    }

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

    @Override
    public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
        super.onReceivedError(view, request, error);
        setProgressBarVisibility(View.GONE);
    }
});

webView.loadUrl(url);

Also add method:

还添加方法:

private void setProgressBarVisibility(int visibility) {
    // If a user returns back, a NPE may occur if WebView is still loading a page and then tries to hide a ProgressBar.
    if (progressBar != null) {
        progressBar.setVisibility(visibility);
    }
}

回答by James Hoang

    myThanh.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);

    final AlertDialog alertDialog = new AlertDialog.Builder(this).create();

    progressBar = ProgressDialog.show(MainActivity.this,"?ang t?i d? li?u",  "Vui lòng ch?...");

    myThanh.setWebViewClient(new WebViewClient() {


        public void onPageFinished(WebView view, String url) {
            if (progressBar.isShowing()) {
                progressBar.dismiss();
            }
        }
    });

回答by Marcelo Gracietti

This simple solution worked for me in KOTLIN:

这个简单的解决方案在KOTLIN 中对我有用

private fun setupWebView() {

    val webViewClient: WebViewClient = object: WebViewClient() {

        override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
            view?.loadUrl(request?.url.toString())
            return super.shouldOverrideUrlLoading(view, request)
        }

        override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
            showProgressDialog()
            super.onPageStarted(view, url, favicon)
        }

        override fun onPageFinished(view: WebView?, url: String?) {
            hideProgressDialog()
            super.onPageFinished(view, url)
        }
    }
    webView.webViewClient = webViewClient

    webView.settings.javaScriptEnabled = true
    webView.settings.defaultTextEncodingName = "utf-8"
}

回答by VIMAL VISHWAKARMA

  @SuppressLint("SetJavaScriptEnabled")
private void init() {
    webView = (WebView) findViewById(R.id.kamal);
    webView.setBackgroundColor(0);
    webView.getSettings().setJavaScriptEnabled(true);
    progressDialog = new ProgressDialog(WebView_Ofline.this);
    progressDialog.setMessage("Loading Please wait...");
    progressDialog.setCancelable(false);
    progressDialog.show();
    webView.setWebViewClient(new WebViewClient() {
        public void onPageFinished(WebView view, String url) {
            try {
                progressDialog.dismiss();
            } catch (Exception e) {
                e.printStackTrace();

            }
        }

    });
}

回答by MazRoid

Paste This in your code and add your URL

将此粘贴到您的代码中并添加您的 URL

   var progressDialog: ProgressDialog? = null

private fun startWebView(url: String) {

    val settings = webView.getSettings()

    settings.setJavaScriptEnabled(true)
    webView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY)

    webView.getSettings().setBuiltInZoomControls(true)
    webView.getSettings().setUseWideViewPort(true)
    webView.getSettings().setLoadWithOverviewMode(true)

    progressDialog = ProgressDialog(this)
    progressDialog!!.setMessage("Loading...")
    progressDialog!!.show()

    webView.setWebViewClient(object : WebViewClient() {
        override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
            view.loadUrl(url)
            return true
        }

        override fun onPageFinished(view: WebView, url: String) {
            if (progressDialog!!.isShowing()) {
                progressDialog!!.dismiss()
            }
        }

        override fun onReceivedError(view: WebView, errorCode: Int, description: String, failingUrl: String) {
            Toast.makeText(this@MainActivity, "Error:$description", Toast.LENGTH_SHORT).show()

        }
    })
    webView.loadUrl(url)
}

回答by Gabriel Bronzatti Moro

You can use something like that:

你可以使用这样的东西:

override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
    super.onPageStarted(view, url, favicon)
    binding.pbLoader.visibility = ProgressBar.VISIBLE
}

override fun onPageCommitVisible(view: WebView?, url: String?) {
    super.onPageCommitVisible(view, url)
    binding.pbLoader.visibility = ProgressBar.GONE
}