Android Implementation of WebView with Progress Bar

  • 2021-11-14 06:54:58
  • OfStack

When loading H5 pages, the loading process may appear blank due to network, page content complexity and other reasons, and the progress bar can effectively improve the user experience

1. Customize the ProgressWebView class


public class ProgressWebView extends WebView {

  private ProgressBar progressbar;

  public ProgressWebView(Context context, AttributeSet attrs) {
    super(context, attrs);
    progressbar = new ProgressBar(context, null,
        android.R.attr.progressBarStyleHorizontal);
    progressbar.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
        5, 0, 0));
    Drawable drawable = context.getResources().getDrawable(R.drawable.progress_bar_states);
    progressbar.setProgressDrawable(drawable);
    addView(progressbar);
    // setWebViewClient(new WebViewClient(){});
    setWebChromeClient(new WebChromeClient());
    // Can I zoom 
    getSettings().setSupportZoom(true);
    getSettings().setBuiltInZoomControls(true);
  }

  public class WebChromeClient extends android.webkit.WebChromeClient {
    @Override
    public void onProgressChanged(WebView view, int newProgress) {
      if (newProgress == 100) {
        progressbar.setVisibility(GONE);
      } else {
        if (progressbar.getVisibility() == GONE)
          progressbar.setVisibility(VISIBLE);
        progressbar.setProgress(newProgress);
      }
      super.onProgressChanged(view, newProgress);
    }
  }

  @Override
  protected void onScrollChanged(int l, int t, int oldl, int oldt) {
    LayoutParams lp = (LayoutParams) progressbar.getLayoutParams();
    lp.x = l;
    lp.y = t;
    progressbar.setLayoutParams(lp);
    super.onScrollChanged(l, t, oldl, oldt);
  }
}

2. Layout file labels are written as custom classes, using and 1 like WebView1

Finally, paste progress_bar_states under drawable under 1


<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
  <item android:id="@android:id/background">
    <shape>
      <corners android:radius="2dp" />
      <gradient
        android:angle="270"
        android:centerColor="#E3E3E3"
        android:endColor="#E6E6E6"
        android:startColor="#C8C8C8" />
    </shape>
  </item>
  <item android:id="@android:id/progress">
    <clip>
      <shape>
        <corners android:radius="2dp" />

        <gradient
          android:centerColor="#4AEA2F"
          android:endColor="#31CE15"
          android:startColor="#5FEC46" />
      </shape>
    </clip>
  </item>
</layer-list>

Related articles: