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

對話框式進度條實作:ProgressDialog 完整示範

編輯:關於 Android 程式設計

先前談過一般進度條的用法,涵蓋標題欄進度與水平進度條兩種形式。不過在實務專案裡,還有一種更常被拿出來的寫法:把進度做成一個獨立彈出的對話框。它在背景執行耗時工作、需要明確告知使用者「請稍候」的場景中特別合適。

版面配置

畫面上只需要一顆按鈕用來觸發,其餘交給程式碼動態產生。

<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" >

    <Button
        android:id="@+id/main_btn_show"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="顯示進度條對話框" />
</LinearLayout>

Activity 端:用 onCreateDialog 管理生命週期

把 ProgressDialog 的建立交給 Activity 的對話框管理機制,的好處是旋轉螢幕等狀態改變時,系統能自動幫你還原與釋放,不必自己寫一堆 null 檢查。

package com.home;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

    private Button showProgressDialogBtn;

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

        showProgressDialogBtn = (Button) findViewById(R.id.main_btn_show);
        showProgressDialogBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                showDialog(0); // 觸發 onCreateDialog
            }
        });
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        ProgressDialog dialog = new ProgressDialog(this);
        dialog.setTitle("測試進度條對話框");
        dialog.setIndeterminate(true);   // 不確定進度,只轉圈
        dialog.setMessage("程序正在加載請稍後。。。");
        dialog.setCancelable(true);      // 允許使用者取消
        return dialog;
    }
}

幾個實務上的細節

setIndeterminate(true) 與 false 是兩種截然不同的情境:前者只適合「不知道還要多久」的等待,後者則要搭配 setProgress() 與 setMax() 顯示百分比。另外,如果任務進行到一半使用者按下返回鍵就關閉對話框,背景執行緒仍 Should 具備中止機制,否則容易出現「畫面已關閉、下載還在跑」的尷尬狀態。

效果如下圖:

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