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

Android 八種 Dialog 用法圖解:從普通提示到自訂版面

編輯:關於 Android 程式設計

Dialog 是 Android 里最常被使用、也最容易被寫得雜亂的元件。本文把八種常見型態一次整理出來,包含普通提示、列表、單選、多選、等待、進度、輸入與自訂版面,最後再說明如何在顯示前後插入自己的邏輯。

一、普通 Dialog

最基礎的形式,透過 AlertDialog.Builder 串起圖示、標題、訊息與按鈕。setXxx 方法都會回傳 Builder 本身,因此可以鏈式呼叫。

兩個按鈕:

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button buttonNormal = (Button) findViewById(R.id.button_normal);
        buttonNormal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showNormalDialog();
            }
        });
    }

    private void showNormalDialog() {
        /* @setIcon 設置圖標
         * @setTitle 設置標題
         * @setMessage 設置提示訊息 */
        final AlertDialog.Builder normalDialog = new AlertDialog.Builder(MainActivity.this);
        normalDialog.setIcon(R.drawable.icon_dialog);
        normalDialog.setTitle("我是一個普通Dialog");
        normalDialog.setMessage("你要點擊哪一個按鈕呢?");
        normalDialog.setPositiveButton("確定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // To-do
            }
        });
        normalDialog.setNegativeButton("關閉", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // To-do
            }
        });
        normalDialog.show();
    }
}

三個按鈕時,中間那颗用 setNeutralButton:

private void showMultiBtnDialog() {
    AlertDialog.Builder normalDialog = new AlertDialog.Builder(MainActivity.this);
    normalDialog.setIcon(R.drawable.icon_dialog);
    normalDialog.setTitle("我是一個普通Dialog")
            .setMessage("你要點擊哪一個按鈕呢?");
    normalDialog.setPositiveButton("按鈕1", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) { }
    });
    normalDialog.setNeutralButton("按鈕2", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) { }
    });
    normalDialog.setNegativeButton("按鈕3", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) { }
    });
    normalDialog.show();
}

二、列表 Dialog

setItems 接受字串陣列,回呼中的 which 就是被點擊的索引(從 0 起算):

private void showListDialog() {
    final String[] items = { "我是1", "我是2", "我是3", "我是4" };
    AlertDialog.Builder listDialog = new AlertDialog.Builder(MainActivity.this);
    listDialog.setTitle("我是一個列表Dialog");
    listDialog.setItems(items, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            Toast.makeText(MainActivity.this, "你點擊了" + items[which],
                    Toast.LENGTH_SHORT).show();
        }
    });
    listDialog.show();
}

三、單選 Dialog

第二個參數是預設選項索引。實作上用一個變數記住選擇,待使用者按確定後才取用,避免選了卻被取消的情況被誤判:

int yourChoice;

private void showSingleChoiceDialog() {
    final String[] items = { "我是1", "我是2", "我是3", "我是4" };
    yourChoice = -1;
    AlertDialog.Builder singleChoiceDialog = new AlertDialog.Builder(MainActivity.this);
    singleChoiceDialog.setTitle("我是一個單選Dialog");
    singleChoiceDialog.setSingleChoiceItems(items, 0, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            yourChoice = which;
        }
    });
    singleChoiceDialog.setPositiveButton("確定", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            if (yourChoice != -1) {
                Toast.makeText(MainActivity.this, "你選擇了" + items[yourChoice],
                        Toast.LENGTH_SHORT).show();
            }
        }
    });
    singleChoiceDialog.show();
}

四、多選 Dialog

第二個參數是初始勾選狀態陣列,第三個回呼帶有 isChecked 指出這次是勾選還是取消:

ArrayList<Integer> yourChoices = new ArrayList<>();

private void showMultiChoiceDialog() {
    final String[] items = { "我是1", "我是2", "我是3", "我是4" };
    final boolean initChoiceSets[] = { false, false, false, false };
    yourChoices.clear();

    AlertDialog.Builder multiChoiceDialog = new AlertDialog.Builder(MainActivity.this);
    multiChoiceDialog.setTitle("我是一個多選Dialog");
    multiChoiceDialog.setMultiChoiceItems(items, initChoiceSets,
            new DialogInterface.OnMultiChoiceClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                    if (isChecked) {
                        yourChoices.add(which);
                    } else {
                        yourChoices.remove(Integer.valueOf(which));
                    }
                }
            });
    multiChoiceDialog.setPositiveButton("確定", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            String str = "";
            for (int i = 0; i < yourChoices.size(); i++) {
                str += items[yourChoices.get(i)] + " ";
            }
            Toast.makeText(MainActivity.this, "你選中了" + str, Toast.LENGTH_SHORT).show();
        }
    });
    multiChoiceDialog.show();
}

這裡有個經典陷阱:yourChoices.remove(which) 傳入的是 int,會被當成索引而非物件,導致刪錯元素,因此必須包成 Integer.valueOf(which) 才會走物件比對。

五、等待 Dialog

具備遮罩能力,可阻擋其他控件互動。設為不可取消後,必須由程式在下載或請求結束時主動關閉:

private void showWaitingDialog() {
    ProgressDialog waitingDialog = new ProgressDialog(MainActivity.this);
    waitingDialog.setTitle("我是一個等待Dialog");
    waitingDialog.setMessage("等待中...");
    waitingDialog.setIndeterminate(true);
    waitingDialog.setCancelable(false);
    waitingDialog.show();
}

六、進度條 Dialog

private void showProgressDialog() {
    final int MAX_PROGRESS = 100;
    final ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
    progressDialog.setProgress(0);
    progressDialog.setTitle("我是一個進度條Dialog");
    progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    progressDialog.setMax(MAX_PROGRESS);
    progressDialog.show();

    // 模擬進度遞增,每 100ms 加 1
    new Thread(new Runnable() {
        @Override
        public void run() {
            int progress = 0;
            while (progress < MAX_PROGRESS) {
                try {
                    Thread.sleep(100);
                    progress++;
                    progressDialog.setProgress(progress);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            progressDialog.cancel();
        }
    }).start();
}

七、輸入 Dialog

用 setView 塞進一個 EditText 即可:

private void showInputDialog() {
    final EditText editText = new EditText(MainActivity.this);
    AlertDialog.Builder inputDialog = new AlertDialog.Builder(MainActivity.this);
    inputDialog.setTitle("我是一個輸入Dialog").setView(editText);
    inputDialog.setPositiveButton("確定", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            Toast.makeText(MainActivity.this, editText.getText().toString(),
                    Toast.LENGTH_SHORT).show();
        }
    }).show();
}

八、自訂 Dialog

版面檔 dialog_customize.xml:

<!-- res/layout/dialog_customize.xml -->
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <EditText
        android:id="@+id/edit_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

用 LayoutInflater 把版面撐開後交給 setView,就能放進任何自訂內容:

private void showCustomizeDialog() {
    AlertDialog.Builder customizeDialog = new AlertDialog.Builder(MainActivity.this);
    final View dialogView = LayoutInflater.from(MainActivity.this)
            .inflate(R.layout.dialog_customize, null);
    customizeDialog.setTitle("我是一個自定義Dialog");
    customizeDialog.setView(dialogView);
    customizeDialog.setPositiveButton("確定", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            EditText edit_text = (EditText) dialogView.findViewById(R.id.edit_text);
            Toast.makeText(MainActivity.this, edit_text.getText().toString(),
                    Toast.LENGTH_SHORT).show();
        }
    });
    customizeDialog.show();
}

九、攔截 create 與 show

若希望在-dialog建立或顯示時做一些事(例如初始化列表、設定預設選項),可以改寫 Builder 的 create() 與 show()。前者只在第一次建立時呼叫,後者每次顯示都會觸發,這個差異在 Dialog 被重複使用時很重要。

private void showListDialog() {
    final String[] items = { "我是1", "我是2", "我是3", "我是4" };
    AlertDialog.Builder listDialog = new AlertDialog.Builder(MainActivity.this) {
        @Override
        public AlertDialog create() {
            items[0] = "我是No.1";
            return super.create();
        }

        @Override
        public AlertDialog show() {
            items[1] = "我是No.2";
            return super.show();
        }
    };
    listDialog.setTitle("我是一個列表Dialog");
    listDialog.setItems(items, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) { }
    });
    /* @setOnDismissListener Dialog 銷毀時調用
     * @setOnCancelListener Dialog 被取消時調用 */
    listDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
        public void onDismiss(DialogInterface dialog) {
            Toast.makeText(getApplicationContext(), "Dialog被銷毀了",
                    Toast.LENGTH_SHORT).show();
        }
    });
    listDialog.show();
}

最後兩點實務建議:ProgressDialog 已被官方標記為 deprecated,因為它在背景執行時無法更新、旋轉螢幕後容易洩漏,改用 Toolbar 加上非阻斷式的進度指示器體驗更好;另外所有 Dialog 都應持有 Activity 而非 Application 的 Context,並在 onStop 時呼叫 dismiss,否則螢幕旋轉後會出現「WindowLeaked」的錯誤日誌。

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