溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Android實現(xiàn)帶進度條的WebView

發(fā)布時間:2020-09-29 13:10:34 來源:腳本之家 閱讀:151 作者:ability_齊 欄目:移動開發(fā)

在加載H5頁面的時候,可能由于網(wǎng)絡、頁面內(nèi)容復雜度等原因,導致加載過程出現(xiàn)空白,加上進度條可以有效提高用戶體驗

一、自定義ProgressWebView類

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());
    //是否可以縮放
    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);
  }
}

二、布局文件標簽寫成自定義的類,使用和一般WebView一致

最后貼一下drawable下的progress_bar_states

<?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>

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持億速云。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI