Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發 >> 中階開發

Android AlertDialog 類別的幾個實用範例

編輯:中階開發

先看 SDK 的官方說明(Class Overview):

A subclass of Dialog that can display one, two or three buttons. If you only want to display a String in this dialog box, use the setMessage() method. If you want to display a more complex view, look up the FrameLayout called "body" and add your view to it:

FrameLayout fl = (FrameLayout) findViewById(R.id.body);
fl.addView(myView, new LayoutParams(FILL_PARENT, WRAP_CONTENT));

The AlertDialog class takes care of automatically setting WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM for you based on whether any views in the dialog return true from View.onCheckIsTextEditor(). Generally you want this set for a Dialog without text editors, so that it will be placed on top of the current input method UI. You can modify this behavior by forcing the flag to your desired mode after calling onCreate(Bundle).

白話整理:AlertDialog 是 Dialog 的子類,可以顯示一到三個按鈕。如果只是要顯示一段文字,用 setMessage() 就好;如果想放進比較複雜的介面,就取得 FrameLayout 中名為 body 的容器,把自己的 View 塞進去。

建立對話框時,需要用 AlertDialog.Builder(Context context) 這個 Builder 來組裝,最後再產生 AlertDialog。以下由簡到繁介紹幾種常見用法。

範例一:含 OK 與 Cancel 兩個按鈕

new AlertDialog.Builder(MyAlertDialog.this)
    // 視情況替換成目前的 Activity 或對應的 XML 視窗
    .setTitle("真的要離開?")                       // 標題
    .setMessage("你確定要離開")                     // 內容
    .setPositiveButton("OK",                        // 確認按鈕
        new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                // 在這裡處理確認後的邏輯
                android.os.Process.killProcess(android.os.Process.myPid());
            }
        })
    .setNegativeButton("Cancel",                    // 取消按鈕
        new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        })
    .show();

範例二:含單選清單的對話框

先準備選項資料。若已在 res/values/strings.xml 中定義好固定字串:

<string name="str_status_1">status_1</string>
<string name="str_status_2">status_2</string>
<string name="str_status_3">status_3</string>
<string name="str_status_4">status_4</string>

在 Java 類別中就可以這樣取值:

final CharSequence[] statusChar = {
        getResources().getString(R.string.str_status_1),
        getResources().getString(R.string.str_status_2),
        getResources().getString(R.string.str_status_3),
        getResources().getString(R.string.str_status_4) };

如果沒有另外定義,直接寫死也可以:

final CharSequence[] statusChar = {
        "status_1", "status_2", "status_3", "status_4" };

接著把它載入 setSingleChoiceItems:

int statusId = 0;                                  // 記錄選擇結果

new AlertDialog.Builder(MyAlertDialog.this)
    .setTitle("真的要離開?")
    .setMessage("你確定要離開")
    .setSingleChoiceItems(statusChar,
            -1,                                    // -1 表示預設不選,因為索引從 0 開始
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    statusId = which + 1;
                    Toast.makeText(MyAlertDialog.this, statusChar[which],
                            Toast.LENGTH_LONG).show();
                }
            })
    .setPositiveButton("OK",
        new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                android.os.Process.killProcess(android.os.Process.myPid());
            }
        })
    .setNegativeButton("Cancel",
        new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        })
    .show();

範例三:使用自訂 View

最後來做一個帶自訂 View 的對話框。首先在 res/layout 下新增一個 XML 檔,例如 statusView.xml:

<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/AbsoluteLayout01"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <TextView
        android:layout_x="20dip"
        android:layout_y="10dip"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="當前狀態資訊" />

    <EditText
        android:id="@+id/etInfo"
        android:singleLine="false"
        android:lines="5"
        android:gravity="top"
        android:layout_width="200dip"
        android:layout_height="200dip"
        android:layout_x="20dip"
        android:layout_y="60dip" />
</AbsoluteLayout>

接著在 Java 類別中把它載入:

// 取得版面配置解析器
LayoutInflater inflater = LayoutInflater.from(MyAlertDialog.this);

// 將 statusView.xml 解析成 View 實例
final View layout = inflater.inflate(R.layout.statusView, null);

// 透過 setView(View) 掛上去即可
new AlertDialog.Builder(MyAlertDialog.this)
    .setView(layout)
    .create()
    .show();

至於按鈕等其他設定,寫法與前面兩個範例相同。想了解更多細節,建議直接查閱官方開發文件。

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