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

Android UI 之 ProgressBar 詳解

編輯:關於 Android 程式設計

1. 應用場景

ProgressBar 主要用在網路請求、資料載入等需要使用者等待的場合。如果完全沒有提示,使用者可能直接退出,甚至誤以為程式壞了。加上 ProgressBar 的目的,就是明確告訴使用者「正在載入」以及「目前進度到哪」,藉此優化使用體驗。

2. 常用屬性

android:max=""                   // 最大進度值,一般為 100
style=""                         // 進度條風格
android:progress=""              // 第一進度
android:secondaryProgress=""     // 第二進度,多用於影片緩存進度顯示
android:indeterminate=""         // 是否為不確定進度
android:indeterminateOnly=""     // 強制使用 indeterminate 模式
android:progressDrawable=""      // 明確進度條的 Drawable
android:indeterminateDrawable="" // 不確定進度的 Drawable
android:indeterminateDuration="" // 不確定模式的動畫間隔時間
android:indeterminateBehavior="" // 不確定模式下播放到最大時的動畫行為
                                 // repeat:從頭開始 | cycle:反向從後往前

3. 系統預設的進度條類型

分類:

條形進度條:style="@android:style/Widget.ProgressBar.Horizontal"
常規圓形進度條:style="@android:style/Widget.ProgressBar"
反向旋轉常規圓形:style="@android:style/Widget.ProgressBar.Inverse"
大號圓形:style="@android:style/Widget.ProgressBar.Large"
反向旋轉大號圓形:style="@android:style/Widget.ProgressBar.Large.Inverse"
小號圓形:style="@android:style/Widget.ProgressBar.Small"
反向旋轉小號圓形:style="@android:style/Widget.ProgressBar.Small.Inverse"

註:還有其他風格,例如 HOLO 風格與 Material 風格(需 API 21 以上),有興趣可以再查。

兩種設置 style 的寫法:

(1)透過內建的 attr 屬性:style="?android:attr/progressBarStyleHorizontal"
(2)直接指定完整 style:style="@android:style/Widget.ProgressBar.Horizontal"

4. 基本用法:進度的更新與讀取

主布局檔:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.andy.androiduiprogressbar.MainActivity">

    <Button
        android:id="@+id/start"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="開始" />

    <ProgressBar
        android:id="@+id/progress"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:max="100"
        android:progress="20"
        android:secondaryProgress="30" />

    <TextView
        android:id="@+id/value"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="value" />
</LinearLayout>

主 Activity:

public class MainActivity extends Activity {
    private Button start;
    private ProgressBar progressBar;
    private TextView value;
    private AsyncTask<Integer, Integer, Integer> myAsyncTask;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        start       = (Button) findViewById(R.id.start);
        progressBar = (ProgressBar) findViewById(R.id.progress);
        value       = (TextView) findViewById(R.id.value);

        myAsyncTask = new AsyncTask<Integer, Integer, Integer>() {
            /** 後台任務結束後的收尾 */
            @Override
            protected void onPostExecute(Integer result) {
                Log.d("info", "myAsyncTask 執行完成");
            }

            /** 更新進度條與文字 */
            @Override
            protected void onProgressUpdate(Integer... values) {
                progressBar.setProgress(values[0]);
                value.setText("當前進度:" + values[0].toString());
            }

            /** 模擬後台工作 */
            @Override
            protected Integer doInBackground(Integer... params) {
                for (int i = 1; i <= 100; i++) {
                    try {
                        Thread.sleep(500);
                        publishProgress(i);   // 觸發 onProgressUpdate
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                return 100;
            }
        };

        start.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                myAsyncTask.execute();
            }
        });
    }
}

效果如下:

5. ProgressDialog 中的進度條

主布局檔:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.andy.androiduiprogressbar.MainActivity">

    <Button
        android:id="@+id/dlgProgressBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="彈出 Progress" />
</LinearLayout>

主 Activity:

public class SecondActivity extends Activity {
    private Button dlgProgressBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);

        dlgProgressBtn = (Button) findViewById(R.id.dlgProgressBtn);
        dlgProgressBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                ProgressDialog progressDialog = new ProgressDialog(SecondActivity.this);
                progressDialog.setIcon(R.drawable.ic_launcher);
                progressDialog.setTitle("彈框進度條標題");
                progressDialog.setMessage("加載中...");
                // STYLE_HORIZONTAL:長條進度條 | STYLE_SPINNER:圓形轉圈
                progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                progressDialog.setCancelable(true);
                progressDialog.setCanceledOnTouchOutside(true);
                // BUTTON_NEGATIVE:取消 | BUTTON_POSITIVE:確認 | BUTTON_NEUTRAL:普通
                progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消",
                        new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Log.d("cancel", "進度條彈框取消");
                    }
                });
                progressDialog.show();
            }
        });
    }
}

效果如下:

6. AlertDialog.Builder 中的自訂進度條

自訂彈框布局 custom_dialog_layout.xml:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.andy.androiduiprogressbar.ThreeActivity">

    <ProgressBar
        android:id="@+id/progress"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:max="100"
        android:progress="20"
        android:secondaryProgress="30" />
</LinearLayout>

主布局 activity_three.xml:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.andy.androiduiprogressbar.ThreeActivity">

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

主 Activity:

public class ThreeActivity extends Activity {
    private Button alertDialogbtn;
    private ProgressBar progress;
    private AlertDialog.Builder builder;   // AlertDialog 構建者
    private AlertDialog progressDialog;    // 實例
    private LayoutInflater minflater;      // 布局加載器
    private LinearLayout mLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_three);

        minflater = (LayoutInflater) getSystemService(this.LAYOUT_INFLATER_SERVICE);
        mLayout = (LinearLayout) minflater.inflate(R.layout.custom_dialog_layout, null);
        progress = (ProgressBar) mLayout.findViewById(R.id.progress);

        alertDialogbtn = (Button) findViewById(R.id.alertDialogbtn);
        alertDialogbtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                progressDialog.show();
            }
        });

        builder = new AlertDialog.Builder(ThreeActivity.this);
        progressDialog = builder.create();
        progressDialog.setIcon(R.drawable.ic_launcher);
        progressDialog.setTitle("progressDialog 標題");
        progressDialog.setMessage("正在加載中...");
        progressDialog.setView(mLayout);            // 套用自訂布局
        progressDialog.setCancelable(true);
        progressDialog.setCanceledOnTouchOutside(true);

        progressDialog.setButton(AlertDialog.BUTTON_POSITIVE, "確認",
                new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(ThreeActivity.this, "點擊了確認", Toast.LENGTH_SHORT).show();
            }
        });
        progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消",
                new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(ThreeActivity.this, "進度條彈框取消", Toast.LENGTH_SHORT).show();
            }
        });
    }
}

效果如下:

7. 標題列下方的進度條

這種做法利用的是 Window 的 Feature 機制:

public class FourActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // 必須在 setContentView 之前申請 FEATURE_PROGRESS
        requestWindowFeature(Window.FEATURE_PROGRESS);
        setProgressBarVisibility(true);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_four);

        setProgress(30);                        // 第一進度
        setProgressBarIndeterminate(false);     // 是否為不確定樣式
        setSecondaryProgress(40);               // 第二進度
    }
}

要補充的是,ProgressDialog 從 API 26 起已被標記為 deprecated,官方建議改用 ProgressBar 搭配自訂 DialogFragment 或 Snackbar 呈現載入狀態;而標題列進度條這套 Window Feature 也屬於較早期的寫法。新專案中優先考慮 Toolbar 搭配自訂 ProgressBar 的組合,會更好維護。

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