星期日, 10月 02, 2011

Creating an AlertDialog

Android應用程式學習筆記

Creating an AlertDialog

AlertDialog是Dialog類的延伸,它有能力建造大部分的對話框的使用者介面且是建議使用的對話框形式,你應該使用有任何以下屬性的對話框:

  • A tile
  • A text message
  • one , two or three buttons
  • A list of selected items (with optional checkboxs or radio buttons)
要創建AlertDialog,使用AlertDialog.Builder子類,用AlertDialog.Builder(context)取得Builder物件然後用公開方法來定義所有AlertDialog的特性,在完成Builder物件之後,用create()方法取得AlertDialog物件。

以下的主題要放在如何使用AlertDialog.Builder類定義AlertDialog的特性。


Adding buttons

使用set...Button()方法創建有並肩按鈕的AlertDialog,如右圖所示。


AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?")
       .setCancelable(false)
       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog, int id) {
                MyActivity.this.finish();
           }
       })
       .setNegativeButton("No", new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
           }
       });
AlertDialog alert = builder.create();

首先,setMessage(CharSequence)增加一個訊息到對話框,接著,setCancelable(boolean)設定對話框為not cancelable(所以用戶無法透過back鍵來關閉對話框)。為每個按鈕使用一個set...Button()方法,比如,setPositiveButton(),它接收按鈕的名稱及一個DialogInterface.onClickListener,定義當用戶選擇按鈕對應的動作。

Adding a list

使用setItem()方法創建有可選擇的項目列表的對話框,如右圖所示。

final CharSequence[] items = {"Red", "Green", "Blue"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Pick a color");
builder.setItems(items, new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int item) {
        Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
    }
});
AlertDialog alert = builder.create();

首先,setTitle(CharSequence)設定對話框標題,接著,setItem()增加一個可選擇項目列表,它接收一個用來顯示的項目陣列及一個DialogInterface.onClickListener,定義用戶選擇項目對應的動作。


Adding checkboxs and radio buttons

使用setMultiChoiceItems()或setSingleChoiceItems()方法創建複選或單選的選擇列表於對話框中。如果你在onCreateDialog()方法中創建其中一種可選擇的列表,Android系統將為你管理列表的狀態,只要Activity是活耀的,對話框會記住先前被選擇的項目,但是當用戶結束activity,選擇就會遺失。

創建有單選項目的列表的對話框,使用先前的例子的程式碼,但setItem()方法用setSingleChoiceItem()方法代替。

final CharSequence[] items = {"Red", "Green", "Blue"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Pick a color");
builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int item) {
        Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
    }
});
AlertDialog alert = builder.create();

setSingleChoiceItem()的第二個參數是為checkedItem的整數數值,它表示預設被選擇的項目,使用"-1"表示預設沒有項目被選擇。

沒有留言:

張貼留言