這個例子的主Activity定義在AlertDialogSamples.java 主要用來介紹類AlertDialog的用法,AlertDialog提供的功能是多 樣的:
顯示訊息給使用者,並可提供一到三個按鈕(OK, Cancel ,Yes ,No)用於選擇或是顯示警告。
顯示一個列表 以供使用者選擇,列表中可以是Radio Button (單選),Check button (多選)
顯示文字框來接受使用者輸入等。
建立AlertDialog一般是通過AlertDialog.Builder來構造:
AlertDialog.Builder ad=new AlertDialog.Builder(context);
之後可以為這個AlergDialog設定標題,顯示的資訊,需要顯示的Buttons等。然後調用 ad.show來顯示這 個對話方塊。
為了避免每次顯示對話方塊都建立一個Dialog對象,Android提供兩個方法 onCreateDialog和onPrepareDialog 事件來管理對話方塊的建立。
通過重載onCreateDialog,可以根據需要(如執行showDialog時)建立所需對話方塊執行個體。而 在建立這個對話方塊執行個體後,在每次showDialog之前,如果需要對這個對話方塊做些修改可以重載onPrepareDialog方法來實現。 原 理和Android管理Menu的方法類似。
下面給出使用AlertDialog的一般步驟。因為在onCreateDialog可能建立多個Dialog 樣本,所以必須先定義一個Dialog的ID。
private static final int DIALOG_YES_NO_MESSAGE = 1;
然後重 載onCreateDialog,參數id為Dialog ID,可以根據id來建立需要的Dialog執行個體。
@Override protected Dialog onCreateDialog(int id) { switch (id) { case DIALOG_YES_NO_MESSAGE: return new AlertDialog.Builder(AlertDialogSamples.this) .setIcon(R.drawable.alert_dialog_icon) .setTitle(R.string.alert_dialog_two_buttons_title) .setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { /* User clicked OK so do some stuff */ } }) .setNegativeButton(R.string.alert_dialog_cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { /* User clicked Cancel so do some stuff */ } }) .create(); ...
顯示Dialog
showDialog(DIALOG_YES_NO_MESSAGE);
App->Dialog通過八個例子來說明 AlertDialog的多種用法:
OK Cancel dialog with a message