
第十二課:使用Dialog
Dialog是個在當前activty下顯示的小視窗,跟用戶作短暫的互動。常用的dialog有AlertDialog, ProgressDialog,DatePickerDialog等。你可以在activity中使用dialog,但官方文件也建議在 activity的onCreateDialog創建dialog,並在希望調用時通過showDialog(int)來呼叫相應的dialog。那個int會 直接傳到onCreateDialog這個call back function中,因此你可以在onCreateDialog中處理多個dialog。
為什麼要在onCreateDialog創建dialog呢?原來,如果你在這裡創建的話,android就會幫你自動暫存起來並加以管理,下次你呼叫同一個dialog的時候,不必再建立一次,減少使用資源。那麼如果想更改dialog怎麼辦呢?你可以使用另一個名為onPrepareDialog的callback。不論dialog是已建立,它也要經過onPrepareDialog的處理。詳細請參考官方文件。
在demo中,我們要建立三個不同的dialog:兩個AlertDialog,和一個ProgressDialog。 把btnClose,btnGender,btnProgress三個button加到layout,然後當它們onClick時,都呼叫showDialog(int)。
private static final int DIALOG_CLOSE = 0; private static final int DIALOG_GENDER = 1; private static final int DIALOG_PROGRESS = 2;
showDialog(DIALOG_CLOSE);
showDialog(DIALOG_GENDER);
showDialog(DIALOG_DIALOG_PROGRESS);
在activity中override onCreateDialog及onPrepareDialog。在它們中加入switch回應不同的dialog no(我們剛自定的 int DIALOG_CLOSE,DIALOG_GENDER,DIALOG_PROGRESS)。在各個case,分別建立不同的dialog。
case DIALOG_CLOSE:
AlertDialog.Builder bc = new AlertDialog.Builder(DialogDemoActivity.this);
bc.setMessage("Do you want to close it?")
.setCancelable(false) //cannot use back button to cancel
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
DialogDemoActivity.this.finish();
}
}).setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
return bc.create();
case DIALOG_GENDER:
final CharSequence[] genders = {"MALE", "FEMALE"};
AlertDialog.Builder bg = new AlertDialog.Builder(this);
bg.setTitle("Please selct your gender.")
.setItems(genders, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), genders[which], Toast.LENGTH_SHORT).show();
}
});
return bg.create();
case DIALOG_PROGRESS:
ProgressDialog dp = ProgressDialog.show(DialogDemoActivity.this, "Loading", "Please wait moment...");
dp.setCancelable(true); //use cancel button to cancel it
return dp;
第一個dialog是詢問用戶是否要關閉activity,第二個是讓用戶在一個list中選取性別,第三個是顯示loading(用戶可 按back按鈕退出)。請留意setCancelable是決定這dialog是否可以按back按鈕來退出。
在onPrepareDialog中,我們嘗試更改每呼叫時的message。
case DIALOG_CLOSE:
counter++;
((AlertDialog)dialog).setMessage("Do you want to close it? (" + counter + ")");
break;
Download: DialogDemo