Thursday, 6 August 2015

android, make a progress bar for your webview



First, as i mentioned: the webView document of showing progress is out of date: http://baiduhix.blogspot.co.uk/2015/08/androidutilandroidruntimeexception.html

So we have to create the progress bar ourself. (very simple and easy!!!)

Solution:

layout:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"    android:orientation="vertical"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    android:paddingBottom="@dimen/activity_vertical_margin"    android:id="@+id/xxxx"    tools:context="com.xxx.policiesviewer.fragmentsolution.fragments.ItemDetailFragment"    >

    <ProgressBar        style="?android:attr/progressBarStyleHorizontal"        android:layout_width="fill_parent"        android:layout_height="3px"        android:max="100"        android:id="@+id/progressBar" />

    <WebView        android:layout_width="match_parent"        android:layout_height="match_parent"        android:id="@+id/webView"        android:layout_centerVertical="true"        android:layout_centerHorizontal="true" />

</LinearLayout>


Code:


webView.setWebChromeClient(new WebChromeClient() {
    public void onProgressChanged(WebView view, int progress) {
        if(progressBar != null) {
            progressBar.setVisibility(View.VISIBLE);
            progressBar.setProgress(progress);
        }
    }
});


webView.setWebViewClient(new WebViewClient() {
    @Override    public void onPageFinished(WebView view, String url) {
        progressBar.setVisibility(View.GONE);
    }
});


Note: I called "progressBar.setVisibility(View.GONE);" in a wrong place. because "onPageFinished" function will get called so many times.


So maybe this is better:

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












No comments:

Post a comment