开发者

AlertDialog sends no callback when created

I have this simple code:

AlertDialog dialog = new AlertDialog.Builder(this).create();

dialog.setTitle ("Alert title");
dialog.setMessage ("This is an alert");

dialog.show();

The dialog is shown but my Activity receives no callbacks. No onPrepareDialog, nothing.

Can I somehow开发者_如何学编程 hook AlertDialog without implementing a custom class extending AlertDialog?

Thanks.


AlertDialog dialog;
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Alert title").setMessage("This is an alert");
builder.setPositiveButton("Ok", new Dialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {

}
});
dialog = builder.create();
dialog.show();


onPrepareDialog is only called for dialogs managed by an Activity (i.e. dialogs created and returned with Activity.onCreateDialog(int) and shown via Activity.showDialog(int)). Since you are creating and showing a dialog directly, these methods will not be called.

See Creating Dialogs for more information on managed dialogs.

To respond to use input - like button clicks - you'll want to use the builder methods as demonstrated by alezhka's answer.


AlertDialog alertDialog;    
AlertDialog.Builder builder = new AlertDialog.Builder(this);

    builder.setMessage("your message");
    builder.setTitle("Alert message");
    builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            // TODO Auto-generated method stub

        }
    });
    builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            // TODO Auto-generated method stub

        }
    });
    alertDialog = builder.create();
    alertDialog.show();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜