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

Android Dialog 全攻略:八種常用對話框實作解析

編輯:關於 Android 程式設計

對話框(Dialog)是 Android 中最常見的互動元件之一,從簡單的確認提示到自訂輸入表單,幾乎每個 App 都會用到。本文把開發中最常出現的八種 Dialog 形式整理成一份可直接套用的範例集,包含版面配置與完整程式碼。

一、主畫面版面配置

先用八個按鈕把各種 Dialog 串起來,每個按鈕對應一種型態。

<ScrollView xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/screen"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical">

        <ImageView
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:src="@drawable/jay" />

        <Button android:id="@+id/button0" android:layout_width="fill_parent"
            android:layout_height="wrap_content" android:text="確定取消資訊框" />
        <Button android:id="@+id/button1" android:layout_width="fill_parent"
            android:layout_height="wrap_content" android:text="多按鈕資訊框" />
        <Button android:id="@+id/button2" android:layout_width="fill_parent"
            android:layout_height="wrap_content" android:text="列表框" />
        <Button android:id="@+id/button3" android:layout_width="fill_parent"
            android:layout_height="wrap_content" android:text="進度條框" />
        <Button android:id="@+id/button4" android:layout_width="fill_parent"
            android:layout_height="wrap_content" android:text="單選列表框" />
        <Button android:id="@+id/button5" android:layout_width="fill_parent"
            android:layout_height="wrap_content" android:text="多選列表框" />
        <Button android:id="@+id/button6" android:layout_width="fill_parent"
            android:layout_height="wrap_content" android:text="自訂版面" />
        <Button android:id="@+id/button7" android:layout_width="fill_parent"
            android:layout_height="wrap_content" android:text="讀取進度框" />
    </LinearLayout>
</ScrollView>

二、自訂 Dialog 的版面

需要讓使用者輸入資料時,就得自己排一份版面,再用 setView() 塞進 Dialog。

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/dialog"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <LinearLayout android:id="@+id/dialogname"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView android:id="@+id/tvUserName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="姓名:" />
        <EditText android:id="@+id/etUserName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:minWidth="200dip" />
    </LinearLayout>

    <LinearLayout android:id="@+id/dialognum"
        android:layout_below="@+id/dialogname"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView android:id="@+id/tvPassWord"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="密碼:" />
        <EditText android:id="@+id/etPassWord"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:minWidth="200dip" />
    </LinearLayout>
</RelativeLayout>

三、Activity 中的完整實作

public class MainDialog extends Activity implements Runnable {

    private static final int DIALOG_0 = 1; // 確定取消資訊框
    private static final int DIALOG_1 = 2; // 多按鈕資訊框
    private static final int DIALOG_2 = 3; // 列表框
    private static final int DIALOG_3 = 4; // 進度條框
    private static final int DIALOG_4 = 5; // 單選列表框
    private static final int DIALOG_5 = 6; // 多選列表框
    private static final int DIALOG_6 = 7; // 自訂版面
    private static final int DIALOG_7 = 8; // 讀取進度框

    private static final int MAX_PROGRESS = 100;
    private ProgressDialog mProgressDialog = null;

    final String[] mItems = {"item0", "item1", "item2", "item3", "item4", "item5", "item6"};
    int mSingleChoiceID = -1;
    ArrayList<Integer> MultiChoiceID = new ArrayList<Integer>();

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

        bind(R.id.button0, DIALOG_0);
        bind(R.id.button1, DIALOG_1);
        bind(R.id.button2, DIALOG_2);
        bind(R.id.button3, DIALOG_3);
        bind(R.id.button4, DIALOG_4);
        bind(R.id.button5, DIALOG_5);
        bind(R.id.button6, DIALOG_6);
        bind(R.id.button7, DIALOG_7);
    }

    private void bind(int viewId, final int dialogId) {
        Button button = (Button) findViewById(viewId);
        button.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                if (dialogId == DIALOG_3) {
                    CreatDialog(dialogId);
                    mProgressDialog.setProgress(0);
                } else {
                    CreatDialog(dialogId);
                }
            }
        });
    }
}

四、CreatDialog 方法逐項拆解

public void CreatDialog(int id) {
    AlertDialog.Builder builder = new AlertDialog.Builder(MainDialog.this);

    switch (id) {
        case DIALOG_0: // 兩顆按鈕的確認框
            builder.setIcon(R.drawable.icon);
            builder.setTitle("你確定要離開嗎?");
            builder.setPositiveButton("確定", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    showDialog("你選擇了確定");
                }
            });
            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    showDialog("你選擇了取消");
                }
            });
            break;

        case DIALOG_1: // 三顆按鈕,靠 setNeutralButton 補上第三個選項
            builder.setIcon(R.drawable.icon);
            builder.setTitle("投票");
            builder.setMessage("您認為什麼樣的內容能吸引您?");
            builder.setPositiveButton("有趣味的", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    showDialog("你選擇了有趣味的");
                }
            });
            builder.setNeutralButton("有思想的", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    showDialog("你選擇了有思想的");
                }
            });
            builder.setNegativeButton("主題強的", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    showDialog("你選擇了主題強的");
                }
            });
            break;

        case DIALOG_2: // 純列表,點完即關閉
            builder.setTitle("列表選擇框");
            builder.setItems(mItems, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    showDialog("你選擇的 id 為 " + which + " , " + mItems[which]);
                }
            });
            break;

        case DIALOG_3: // 水平進度條,搭配子執行緒推進
            mProgressDialog = new ProgressDialog(MainDialog.this);
            mProgressDialog.setIcon(R.drawable.icon);
            mProgressDialog.setTitle("進度條視窗");
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            mProgressDialog.setMax(MAX_PROGRESS);
            mProgressDialog.setButton("確定", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) { }
            });
            mProgressDialog.setButton2("取消", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) { }
            });
            mProgressDialog.show();
            new Thread(this).start();
            return;

        case DIALOG_4: // 單選
            mSingleChoiceID = -1;
            builder.setIcon(R.drawable.icon);
            builder.setTitle("單項選擇");
            builder.setSingleChoiceItems(mItems, 0, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    mSingleChoiceID = whichButton;
                    showDialog("你選擇的 id 為 " + whichButton + " , " + mItems[whichButton]);
                }
            });
            builder.setPositiveButton("確定", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    if (mSingleChoiceID > 0) {
                        showDialog("你選擇的是 " + mSingleChoiceID);
                    }
                }
            });
            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) { }
            });
            break;

        case DIALOG_5: // 多選,自己維護已勾選的集合
            MultiChoiceID.clear();
            builder.setIcon(R.drawable.icon);
            builder.setTitle("多項選擇");
            builder.setMultiChoiceItems(mItems,
                new boolean[]{false, false, false, false, false, false, false},
                new DialogInterface.OnMultiChoiceClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton, boolean isChecked) {
                        if (isChecked) {
                            MultiChoiceID.add(whichButton);
                            showDialog("你選擇的 id 為 " + whichButton + " , " + mItems[whichButton]);
                        } else {
                            MultiChoiceID.remove(Integer.valueOf(whichButton));
                        }
                    }
                });
            builder.setPositiveButton("確定", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    String str = "";
                    for (int i = 0; i < MultiChoiceID.size(); i++) {
                        str += mItems[MultiChoiceID.get(i)] + ", ";
                    }
                    showDialog("你選擇的是 " + str);
                }
            });
            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) { }
            });
            break;

        case DIALOG_6: // 自訂版面
            LayoutInflater factory = LayoutInflater.from(this);
            final View textEntryView = factory.inflate(R.layout.test, null);
            builder.setIcon(R.drawable.icon);
            builder.setTitle("自訂輸入框");
            builder.setView(textEntryView);
            builder.setPositiveButton("確定", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    EditText userName = (EditText) textEntryView.findViewById(R.id.etUserName);
                    EditText password = (EditText) textEntryView.findViewById(R.id.etPassWord);
                    showDialog("姓名:" + userName.getText().toString()
                             + " 密碼:" + password.getText().toString());
                }
            });
            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) { }
            });
            break;

        case DIALOG_7: // 不確定時長的轉圈圈
            mProgressDialog = new ProgressDialog(this);
            mProgressDialog.setTitle("讀取中");
            mProgressDialog.setMessage("正在讀取,請稍候");
            mProgressDialog.setIndeterminate(true);
            mProgressDialog.setCancelable(true);
            mProgressDialog.show();
            return;
    }
    builder.create().show();
}

private void showDialog(String str) {
    new AlertDialog.Builder(MainDialog.this).setMessage(str).show();
}

@Override
public void run() {
    int progress = 0;
    while (progress < MAX_PROGRESS) {
        try {
            Thread.sleep(100);
            progress++;
            mProgressDialog.incrementProgressBy(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

重點整理

  • 按鈕數量決定方法:兩顆用 Positive/Negative,三顆再加上 Neutral。
  • setItems() 適合單純清單;需要「選完再按確定」才用 SingleChoice / MultiChoice。
  • 多選的狀態不會自動幫你記,必須自己用集合維護勾選結果。
  • 進度條 Dialog 建議用子執行緒推進,避免佔用主執行緒造成 ANR。
  • 自訂版面時,記得是從 textEntryView 而非 Activity 去 findViewById。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved