Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

ProgressBar 圓形進度條換色教學:用 indeterminateDrawable 完成漸層效果

編輯:關於 Android 程式設計

「為什麼我的圓形進度條不能改顏色?」這是初學者常問的問題。原因在於圓形(不確定進度)模式的 ProgressBar,其轉盤外觀並不是由 progressTint 這類屬性控制,而是由 indeterminateDrawable 這個可繪製物件決定。換句话说:要改色,就得換掉那張「圖」。

步驟一:在版面配置中指定自訂 drawable

 <ProgressBar
     android:id="@+id/progressbar"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:indeterminateDrawable="@drawable/progressbar" /> 

步驟二:建立 drawable/progressbar.xml

用 animated-rotate 包一層 shape,就能自訂轉盤的形狀與顏色。這裡示範三色的 sweep 漸層:

 <?xml version="1.0" encoding="utf-8"?>
<animated-rotate xmlns:android="https://schemas.android.com/apk/res/android"
     android:pivotX="50%"
     android:pivotY="50%"
     android:fromDegrees="0"
     android:toDegrees="360">

     <shape
         android:shape="ring"
         android:innerRadiusRatio="3"
         android:thicknessRatio="8"
         android:useLevel="false">

         <gradient
             android:type="sweep"
             android:useLevel="false"
             android:startColor="#6BD3FF"
             android:centerColor="#FF7121"
             android:centerY="0.50"
             android:endColor="#FFFF00" />
     </shape>
</animated-rotate> 

效果預覽

參數怎麼調?

  • shape="ring":一定要是 ring,改成 oval 會變成實心圓。若還是想用 oval,可搭配 <stroke> 畫出中空環形。
  • innerRadiusRatio / thicknessRatio:內圈半徑與環寬的比例。數值越小,環形越粗。兩者需搭配調整,只改一個會讓比例失衡。
  • gradient type="sweep":掃描式漸層,顏色繞一圈後銜接回起點。這也是為什麼首尾色(#6BD3FF 與 #FFFF00)色差明顯時,轉動會特別有动感。
  • fromDegrees / toDegrees:動畫的旋轉範圍,0 到 360 就是等速旋轉一圈。

若只想單純換一個顏色

不需要漸層的話,直接在 shape 裡寫 <solid android:color="#FF0000" /> 即可。另外,從 API 21 起也可以不改 drawable,改用 android:indeterminateTint 與 android:indeterminateTintMode 直接替既有的進度條上色,這在維護第三方 UI 時更省事。

水平進度條是另一回事

本文示範的是圓形(不確定進度)進度條。若你要處理的是水平進度條,該改的是 progressDrawable,其結構需要包含 background、secondaryProgress 與 progress 三層 <clip>,設定方式完全不同,別把兩者搞混。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved