背景
Android花樣loading進度條系列文章主要講解如何自定義所需的進度條,包括水平、圓形、環形、圓弧形、不規則形狀等。
本篇我們從水平進度條講起,主要是ProgressBar的水平樣式應用。
進度條控件
Android提供的ProgressBar控件有水平、圓形兩種形態,套用不同的主題可以實現不同的大小,基本上美觀一點的設計在實現的時候都需要自定義ProgressBar樣式。
這裏講水平ProgressBar的樣式更換方法。
進度條樣式自定義
progressDrawable屬性可爲ProgressBar更換指定繪圖方式。適合網頁加載提示的進度條樣式效果爲:
(圖中紅色條爲進度指示條,紅色背後的白色爲背景色)
爲此,我們寫了pro_webview.xml作爲progressDrawable引用的文件,內容如下:
<?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>
<solid android:color="@color/white" />
</shape>
</item>
<!-- 第二進度條顏色 -->
<item android:id="@android:id/secondaryProgress">
<clip>
<shape>
<solid android:color="@color/white" />
</shape>
</clip>
</item>
<!-- 進度條 -->
<item android:id="@android:id/progress">
<clip>
<shape>
<solid android:color="@color/red_web" />
</shape>
</clip>
</item>
</layer-list>
作幾點說明:
- @android:id/background:其對應的item表示進度條的背景色。
- @android:id/secondaryProgress:其對應的item爲第二進度條,一般表示緩衝進度條,比如音視頻在播放的時候會緩衝數據,緩衝表示數據加載效果,而播放過程則使用第一進度條來顯示了。第二進度條在網頁加載中用不到,所以就設成白色了,和背景色一樣。
- @android:id/progress:其對應的item爲進度指示條,可以理解爲第一進度條,網頁加載的進度在這裏使用紅色表示。
- 因爲進度條是隨着加載情況可以動態變化的,所progress、secondaryProgress的樣式設置不能使用單純的color或shape,需要用到clip標籤,因爲ClipDrawable可以很好地裁剪顯示(這塊是Android控件實現上的事情了,開發者不用管)。
配置進度條屬性
將pro_webview.xml中設置的進度樣式應用到ProgressBar屬性中,代碼如下:
<ProgressBar
android:id="@+id/pro_webview"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="4dip"
android:max="100"
android:progress="0"
android:progressDrawable="@drawable/pro_webview"
android:secondaryProgress="0" />
就可以在代碼中使用設置好的ProgressBar來顯示加載效果了。
與WebView結合
WebView在加載網頁時候有接口可以計算出進度,通過不斷更新ProgressBar的進度值,達到進度條隨網頁內容加載而動態變化的效果。動畫如下:
更新ProgressBar的進度值的代碼:
...
webView.setWebChromeClient(webChromeClient);
...
// 獲取加載進度
private WebChromeClient webChromeClient = new WebChromeClient() {
@Override
public void onProgressChanged(WebView view, int newProgress) {
if (newProgress == 100) {
proWebView.setVisibility(View.GONE);
} else {
if (proWebView.getVisibility() == View.GONE) {
proWebView.setVisibility(View.VISIBLE);
}
proWebView.setProgress(newProgress);
}
super.onProgressChanged(view, newProgress);
}
};
通過監聽網頁加載newProgress來判斷是否顯示進度條,當達到100時隱藏進度條,未達到100時,更新進度條的指示值就可以了。
總結
本篇從比較簡單的水平網頁加載進度條入手,講解水平進度條的使用和樣式修改方法。用到的進度條ProgressBar爲Android原生的控件,後續的文章將從自定義控件的角度使用Canvas來繪製進度。