如何在Android上显示警告对话框?

我想显示一个对话框/弹出窗口,并向用户显示一条消息,显示“您确定要删除此条目吗?” 用一个按钮说'删除'。 当Delete被触摸时,它应该删除该条目,否则没有。

我为这些按钮编写了一个点击监听器,但是如何调用对话框或弹出框及其功能?


您可以使用以下警报生成器:

    AlertDialog.Builder builder;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        builder = new AlertDialog.Builder(context, android.R.style.Theme_Material_Dialog_Alert);
    } else {
        builder = new AlertDialog.Builder(context);
    }
    builder.setTitle("Delete entry")
    .setMessage("Are you sure you want to delete this entry?")
    .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) { 
            // continue with delete
        }
     })
    .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) { 
            // do nothing
        }
     })
    .setIcon(android.R.drawable.ic_dialog_alert)
    .show();

试试这个代码:

AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
builder1.setMessage("Write your message here.");
builder1.setCancelable(true);

builder1.setPositiveButton(
    "Yes",
    new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            dialog.cancel();
        }
    });

builder1.setNegativeButton(
    "No",
    new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            dialog.cancel();
        }
    });

AlertDialog alert11 = builder1.create();
alert11.show();

David Hedlund发布的代码给了我错误:

无法添加窗口 - 标记null无效

如果您收到相同的错误,请使用下面的代码。 有用!!

runOnUiThread(new Runnable() {
    @Override
    public void run() {

        if (!isFinishing()){
            new AlertDialog.Builder(YourActivity.this)
              .setTitle("Your Alert")
              .setMessage("Your Message")
              .setCancelable(false)
              .setPositiveButton("ok", new OnClickListener() {
                  @Override
                  public void onClick(DialogInterface dialog, int which) {
                      // Whatever...
                  }
              }).show();
        }
    }
});
链接地址: http://www.djcxy.com/p/26921.html

上一篇: How do I display an alert dialog on Android?

下一篇: Insert multiple images in for