Android AlertDialog
If I take this code and put it in a method I can't get it visible. Could someone help me with this problem?
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)
开发者_JAVA百科 {
Activity.this.finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id)
{
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
private final static int DIALOG_XYZ = 0;
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_XYZ:
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) {
Activity.this.finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
Dialog alert = builder.create();
return alert;
}
return null;
}
Then when you want to show the dialog (from where-ever, just do -
showDialog(DIALOG_XYZ);
Note: As @Hyberboreus hinted, you cannot show the alert dialog on a non-UI thread such as another thread that is running or a service, etc. If that is something you want, look at AsyncTask examples available on the developer's site that tell you how to synchronize background threads with the UI threads and update the UI. HTH.
精彩评论