There are three ways to implement a dialog in Android: .
1. Using the Dialog class (or its extensions) As well
as the general-purpose AlertDialog class, Android
includes a number of specialist classes that extend
Dialog.
2.Dialog-themed Activities You can apply the
dialog theme to a regular Activity to give it the
appearance of a standard dialog box.
3.Toasts Toasts are special non-modal transient message boxes, often used by Broadcast
Receivers and Services to notify users of events occurring in the background.
Creating a new dialog using the Dialog class
Dialog d = new Dialog(MyActivity.this);
// Have the new window tint and blur the window it
// obscures.
Window window = d.getWindow();
window.setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND,WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
// Set the title
d.setTitle("Dialog Title");
// Inflate the layout
d.setContentView(R.layout.dialog_view);
// Find the TextView used in the layout
// and set its text value
TextView text = (TextView)d.findViewById(R.id.dialogTextView);
text.setText("This is the text in my dialog");
Once it’s configured to your liking, use the show method to display it.
d.show();
The Alert Dialog Class
AlertDialog.Builder ad = new AlertDialog.Builder(context);
Context context = MyActivity.this;
String title = "It is Pitch Black";
String message = "You are likely to be eaten by a grue.";
String button1String = "Go Back";
String button2String = "Move Forward";
AlertDialog.Builder ad = new AlertDialog.Builder(context);
ad.setTitle(title);
ad.setMessage(message);
ad.setPositiveButton(button1String,new OnClickListener() {
public void onClick(DialogInterface dialog, int arg1) {
eatenByGrue();
}
});
ad.setNegativeButton(button2String,
new OnClickListener(){
public void onClick(DialogInterface dialog, int arg1) {
// do nothing
}
});
ad.setCancelable(true);
ad.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface dialog) {
eatenByGrue();
}
});
To display an Alert Dialog that you’ve created call show:
ad.show();
Managing and Displaying Dialogs
static final private int TIME_DIALOG = 1;
@Override
public Dialog onCreateDialog(int id) {
switch(id) {
case (TIME_DIALOG) :
AlertDialog.Builder timeDialog = new AlertDialog.Builder(this)
timeDialog.setTitle("The Current Time Is...");
timeDialog.setMessage("Now");
return timeDialog.create();
}
return null;
}
@Override
public void onPrepareDialog(int id, Dialog dialog) {
switch(id) {
case (TIME_DIALOG) :
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
Date currentTime = new Date(java.lang.System.currentTimeMillis());
String dateString = sdf.format(currentTime);
AlertDialog timeDialog = (AlertDialog)dialog;
timeDialog.setMessage(dateString);
break;
}
}
外部调用 showDialog(TIME_DIALOG);