Java Android中WebView加载URL时如何显示进度条?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31634963/
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-11 11:20:18  来源:igfitidea点击:

How to display a progress bar when WebView loads a URL, in Android ?

javaandroidxmlwebview

提问by Rinku

I am new in android apps development and learning it.

我是 android 应用程序开发和学习的新手。

I have developed an application which loads a website link using a WebView. And it's working fine.

我开发了一个应用程序,它使用WebView. 它工作正常。

But I am facing problems to display and hide progress bar when the WebViewloads a page.

但是我在WebView加载页面时遇到了显示和隐藏进度条的问题。

I want to display a progress bar (Just spinner in center) when the WebView loads the main link and internal links of a website and hide progress bar when page is completely loaded.

我想在 WebView 加载网站的主链接和内部链接时显示进度条(仅在中心微调),并在页面完全加载时隐藏进度条。

My Java code:

我的Java代码:

package in.matebook.myapplication;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;


public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        WebView myWebView = (WebView) findViewById(R.id.webView);
        myWebView.setWebViewClient(new MyWebViewClient());
        WebSettings webSettings = myWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        myWebView.loadUrl("http://www.labnol.org");
    }



    private class MyWebViewClient extends WebViewClient {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            if (Uri.parse(url).getHost().equals("www.labnol.org")) {
                // This is my web site, so do not override; let my WebView load the page
                //or we can add more allowed host in if condition
                return false;
            }
            // Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            startActivity(intent);
            return true;
        }


    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return false;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

And my layout XML code:

还有我的布局 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"
    tools:context=".MainActivity">


    <WebView  xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/webView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        />

    <ProgressBar
        android:id="@+id/progressBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        style="?android:attr/progressBarStyleLarge"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />

</RelativeLayout>

Right now, the progress bar is displayed, but it does not hide.

现在,进度条会显示,但不会隐藏。

When I create progressbarobject and add below line in Java code then the progress bar is not displayed.

当我创建进度条对象并在 Java 代码中添加以下行时,不显示进度条。

progressbar.setVisibility(View.GONE);

I have also tried an other answerbut the progress bar does not work when I click on internal links.

我也尝试过其他答案,但是当我单击内部链接时进度条不起作用。

  1. I want to display progress bar when main page load and hide progress bar when the main page is completely loaded.

  2. I want to display the progress bar again when the user clicks on internal links of the website and same as above, hide the progress bar when the page is completely loaded.

  1. 我想在主页加载时显示进度条,并在主页完全加载时隐藏进度条。

  2. 我想在用户点击网站内部链接时再次显示进度条,与上面相同,当页面完全加载时隐藏进度条。

Please help, I am beginner in Android apps development.

请帮助,我是Android应用程序开发的初学者。

采纳答案by Rishad Appat

try this code... you need webChoromeClient to track the webview load progress...

试试这个代码...你需要 webChoromeClient 来跟踪 webview 加载进度...

webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
    progressBar.setProgress(progress);
    if (progress == 100) {
        progressBar.setVisibility(View.GONE);

    } else {
        progressBar.setVisibility(View.VISIBLE);

    }
 }
});

Replace your webview client with this code....

用此代码替换您的 webview 客户端....

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

回答by Marcelo Gracietti

In case anyone is looking for a Kotlinsolution, this simple one worked for me:

如果有人正在寻找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 Mac Dilshad

Hey guys, I have useful this method, That would surely help you too.

嘿伙计们,我有这个方法很有用,那肯定也会对你有帮助。

XML

XML

<WebView
        android:id="@+id/webid"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

<ProgressBar
    android:id="@+id/progress_bar"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true" />

Java:

爪哇:

WebView webView = (WebView)findViewById(R.id.webid);
WebSettings websettings = webView.getSettings();

webSettings.setJavaScriptEnabled(true);
webSettings.setGeolocationEnabled(true);
webSettings.setSupportMultipleWindows(true);


webView.setWebViewClient(new WebViewClient(){

    public void onPageFinished(WebView view,String url){
       ProgressBar progressbar = (ProgressBar) findViewById(R.id.progress_bar);
       progressbar.setVisibility(View.GONE);
       }
});

回答by Ronit Mankad

Guaranteed Solution:

保证解决方案:

        webView.setWebViewClient(new WebViewClient() {

        @Override
        public void onPageCommitVisible(WebView view, String url) {
            super.onPageCommitVisible(view, url);
            mProgressBar.setVisibility(View.INVISIBLE);
        }
    });

回答by Harshil Shah

I've added following to my code and it worked very well for me.

我在我的代码中添加了以下内容,它对我来说效果很好。

XML:

XML:

   <WebView
    android:id="@+id/updates_webview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"  />

   <ProgressBar
    android:id="@+id/progressBar"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    style="?android:attr/progressBarStyleLarge"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true" />

Java:

爪哇:

public class HelloWebViewClient extends WebViewClient {
    @Override
    public void onPageFinished(WebView view, String url) {
        // TODO Auto-generated method stub
        super.onPageFinished(view, url);
        ProgressBar progressBar =  findViewById(R.id.progressBar1);
        progressBar.setVisibility(View.GONE);
    }
}