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

Android ProgressBar 進度條完整指南:屬性、方法與範例

編輯:關於 Android 程式設計

ProgressBar 的作用

ProgressBar 是 Android 中常見的進度提示元件,用來告訴使用者某項任務正在進行,以及目前完成到什麼程度。它常用於資料下載、檔案讀取、網路請求等情境。除了主進度之外,ProgressBar 也能顯示次要進度,例如播放器載入或緩衝進度。

如果任務長度未知,也可以使用不確定模式,讓進度條以循環動畫表示「正在處理中」。

XML 常用屬性

  • style:可指定預設樣式或水平樣式。
  • android:max:設定進度上限。
  • android:progress:設定目前進度。
  • android:secondaryProgress:設定次要進度。

常用方法

  • getMax:取得進度上限。
  • getProgress:取得目前進度。
  • getSecondaryProgress:取得次要進度。
  • incrementProgressBy:依指定增量更新進度。
  • isIndeterminate:判斷是否處於不確定模式。
  • setIndeterminate:切換不確定模式。
  • setVisibility:控制是否顯示。

簡單範例

以下範例建立一個水平進度條,並透過按鈕增加或減少進度。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <ProgressBar
        android:id="@+id/progress_horizontal"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="200dip"
        android:layout_height="wrap_content"
        android:max="100"
        android:progress="50"
        android:secondaryProgress="75" />

    <Button
        android:id="@+id/increase"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="增加" />

    <Button
        android:id="@+id/decrease"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="減少" />
</LinearLayout>

在 Activity 中,可以透過 incrementProgressBy 更新進度,也可以同步更新視窗標題的進度顯示。

ProgressBar progressHorizontal = findViewById(R.id.progress_horizontal);

findViewById(R.id.increase).setOnClickListener(v ->
    progressHorizontal.incrementProgressBy(1)
);

findViewById(R.id.decrease).setOnClickListener(v ->
    progressHorizontal.incrementProgressBy(-1)
);

小結

ProgressBar 的關鍵在於正確設定 max、progress 與 secondaryProgress,並依需求選擇確定或不確定模式。掌握這些屬性與方法,就能在多數場景中呈現清楚的任務進度。

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