web-dev-qa-db-ja.com

Android WebViewのロード中の進行状況バー

私のアプリケーションには、インターネットからURLをロードするWebViewがあります。現在、ネットワークの速度が遅いために、ページの読み込みに時間がかかり、ユーザーには空白の画面しか表示されません。

ProgressBarが読み込まれている間にWebViewを表示し、ProgessBarが完全に読み込まれたときにWebViewを非表示にします。

ProgressBarAsyncTasksの使用方法は知っていますが、ここに問題があります。

これは、WebViewをロードするために使用するコードです。

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

そして、これは私のカスタムWebViewClientクラス

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

今、ProgressBarsを使用してAsyncTaskを表示を試みた場合、doInBackGround()にURLをロードするコードを提供する必要があると思いますAsyncTaskの関数で、onProgressUpdate()関数を使用して進行状況を表示します。

しかし、doInBackground()内でdoInBackground()非UIスレッドで実行され、mWebView.loadUrl(web_URL) その中。

助言がありますか?明らかな何かが欠けていますか?案内してください。

38
Swayam

ソースコードを確認してください。あなたを助け、あなたの問題を解決します...

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

役立つと思います。

ありがとう。

62
Md Abdul Gafur

WebViewが読み込まれている間にprogressBarを表示し、webViewが完全に読み込まれたときにprogessBarを非表示にします。

次のスニペットが役立ちます。

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

このメソッドでURLを渡します

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);
        }
15
Ishant Garg

ユーザーが(最初の読み込みだけでなく)ページを読み込むたびにプログレスバーを表示したい場合、これを使用できます:

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:

<?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>
6
medskill
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);

メソッドも追加します:

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);
    }
}
5
CoolMind
  @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();

            }
        }

    });
}
1
    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();
            }
        }
    });
1
James Hoang

OnPageFinished()メソッドの進捗状況を不正確にしようとしていますが、あまり良くありません。ウェブビューのレンダリングに時間がかかります。

onPageCommitVisible()を試してください。

val progressBar = ProgressDialog(context)
    progressBar.setCancelable(false)
    progressBar.show()

    web_container.webViewClient = object : WebViewClient() {
        override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
            view.loadUrl(url)
            progressBar.show()
            return true
        }

        override fun onPageCommitVisible(view: WebView?, url: String?) {
            super.onPageCommitVisible(view, url)
            progressBar.dismiss()
        }
    }
0
Hally Trần

この簡単な解決策は[〜#〜] 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"
}
0
    WebView webView;
ProgressDialog progressDialog;

TextView text;
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_web_view);


    String message = getIntent().getStringExtra("key").toString();
    setTitle(message);
    Bundle isNetworkAvailable = getIntent().getExtras();

    String value = "file:///Android_asset/n/o/i/no_connection.html";
    if (isNetworkAvailable()) {
        value = isNetworkAvailable.getString("keyHTML");
    }
    webView = (WebView) findViewById(R.id.kamal);
    webView.loadUrl(value);
    init();
}

private boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

private void init() {
    webView = (WebView) findViewById(R.id.kamal);
    webView.getSettings().setBuiltInZoomControls(true);
    webView.setBackgroundColor(0);
    webView.getSettings().setJavaScriptEnabled(true);
    progressDialog = new ProgressDialog(WebView_Online.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();

            }
        }

    });
}
0

これをコードに貼り付けて、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)
}
0
MazRoid