之前遇到一個問題,發現Android裏的圓形進度條無法固定一個進度,記錄一下解決方法
探究
假設我們在xml中這樣寫:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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"
tools:context=".page.home.HomeFragment">
<ProgressBar
android:indeterminate="false"
android:id="@+id/pbStorage"
android:progress="60"
android:max="100"
android:layout_width="100dp"
android:layout_height="100dp"/>
</FrameLayout>
按照預料的,上面的我們的進度條應該是圓形,且設置indeterminate屬性,應該是固定了進度,但實際效果如下:
進度條是一直在轉動的
之後通過翻閱官方的文檔發現,ProgressBar雖然提供了一個圓形和水平進度條的樣式,但是圓形的樣式它不支持確定進度
我們可以打開其內置的theme來找到答案,如下的2個截圖
解決
那麼我們應該如何解決?很簡單,我們可以從參考上面的水平進度條,設置對應的drawable屬性即可解決
progressDrawable
:用於設置ProgressBar
的進度條樣式。可以通過指定一個drawable資源來定義進度條的外觀。通常用於顯示確定的進度,即進度會從0%到100%之間變化。indeterminateDrawable
:用於設置ProgressBar
在不確定進度時的樣式。當ProgressBar
處於不確定進度(indeterminate)時,進度條會顯示一個循環動畫,而不是固定的進度。通過指定一個drawable資源,可以定義不確定進度時的樣式。
當我們設置Progressbar的 indeterminate
屬性的時候爲true,則ProgressBar使用 indeterminateDrawable
這個外觀,否則則使用 progressDrawable
這個外觀
於是我們可以自定義一個圓形的外觀drawable,名爲 progress_bar_green.xml
(放在drawable資源目錄下),代碼如下:
<?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
android:innerRadiusRatio="3.5"
android:shape="ring"
android:useLevel="false"
android:type="sweep"
android:thicknessRatio="12.0">
<!-- 進度條默認底色 -->
<solid android:color="#f2f2f2"/>
</shape>
</item>
<item android:id="@android:id/progress">
<rotate
android:pivotX="50%"
android:pivotY="50%"
android:fromDegrees="-90"
android:toDegrees="-90">
<shape
android:innerRadiusRatio="3.5"
android:shape="ring"
android:angle="0"
android:type="sweep"
android:thicknessRatio="12.0">
<!-- 進度條顏色 -->
<solid android:color="#33cf59"/>
</shape>
</rotate>
</item>
</layer-list>
PS: 如果想要進度條的圓環寬度變小,可以將
thicknessRatio
屬性調大,如果2個thicknessRatio的數值不一致,則是出現下面這種效果,看需求自行調整
之後xml佈局裏使用此drawable:
<ProgressBar
+ style="@style/Widget.AppCompat.ProgressBar.Horizontal"
+ android:progressDrawable="@drawable/progress_bar_green"
+ android:indeterminate="false"
android:id="@+id/pbStorage"
android:progress="60"
android:max="100"
android:layout_width="100dp"
android:layout_height="100dp"/>
這裏發現必須要使用 Widget.AppCompat.ProgressBar.Horizontal
這個樣式才能使我們的progressDrawable屬性生效,猜測是ProgressBar內部或者Android系統內部應該是固定ProgressBar那個圓形默認樣式爲不確定(且不允許設置爲確定進度)
具體原因就不深究了,有興趣的讀者可以研究研究,在評論區回覆告知我 😄