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

Android 學習筆記:自定義 SeekBar 樣式的完整做法

編輯:關於 Android 程式設計

SeekBar 的默認樣式很難看,但定製它其實不需要任何黑科技——只要看懂谷歌是怎麼定義的,然後覆蓋掉相應屬性即可。

一、先看系統是怎麼定義的

SeekBar 的樣式全部集中在 @android:style/Widget.SeekBar 中:

<style name="Widget.SeekBar">
    <item name="indeterminateOnly">false</item>
    <!-- progressDrawable 定義了背景圖、進度圖和緩衝圖 -->
    <item name="progressDrawable">@drawable/progress_horizontal</item>
    <item name="indeterminateDrawable">@drawable/progress_horizontal</item>
    <item name="minHeight">20dip</item>
    <item name="maxHeight">20dip</item>
    <!-- thumb 定義了滑塊圖片 -->
    <item name="thumb">@drawable/seek_thumb</item>
    <item name="thumbOffset">8dip</item>
    <item name="focusable">true</item>
    <item name="mirrorForRtl">true</item>
</style>

換句話說,只要替換 progressDrawable 和 thumb,樣式就換掉了。

二、自定義 progressDrawable

新建 progress_horizontal.xml,用 layer-list 分層描述背景、緩衝進度與當前進度:

<layer-list xmlns:android="https://schemas.android.com/apk/res/android">

    <!-- 背景圖 -->
    <item android:id="@android:id/background"
          android:drawable="@drawable/seekbar_background" />

    <!-- 緩衝進度圖 -->
    <item android:id="@android:id/secondaryProgress">
        <clip>
            <shape>
                <corners android:radius="5dip" />
                <gradient
                    android:angle="270"
                    android:centerY="0.75"
                    android:centerColor="#80ffb600"
                    android:endColor="#a0ffcb00"
                    android:startColor="#80ffd300" />
            </shape>
        </clip>
    </item>

    <!-- 當前進度圖 -->
    <item android:id="@android:id/progress">
        <clip>
            <shape>
                <corners android:radius="5dip" />
                <solid android:color="@color/blue" />
            </shape>
        </clip>
    </item>
</layer-list>

這裡的關鍵是 clip:它讓 shape 按進度百分比裁剪顯示,三個 id 分別對應 background、secondaryProgress、progress,順序和 id 都不能寫錯。

三、在佈局中使用

<SeekBar
    android:id="@+id/seek_bar"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:layout_marginLeft="4dp"
    android:layout_marginRight="4dp"
    android:max="100"
    android:progress="50"
    android:minHeight="3dp"
    android:maxHeight="3dp"
    android:progressDrawable="@drawable/progress_horizontal"
    android:thumb="@drawable/seekbar_thumb" />

需要特別注意的是 minHeight 與 maxHeight 必須同時設置且取值相同,否則系統默認的 20dip 會把你的細進度條撐成一個粗條——這是定製 SeekBar 最常見的失敗原因。

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