带按钮的警报对话框抛出异常

Alert dialog with button throws exception

我通过以下方式显示警告对话框:

    new AlertDialog.Builder(this)
            .setTitle(R.string.label_searching)
            .setMessage(R.string.label_search_noresults)
            .setCancelable(false)
            .setPositiveButton(DialogInterface.BUTTON_POSITIVE, null)
            .create().show();

但是,抛出了这个异常:

FATAL EXCEPTION: main android.content.res.Resources$NotFoundException: String resource ID #0xffffffff at android.content.res.Resources.getText(Resources.java:242) at android.content.Context.getText(Context.java:282) at android.app.AlertDialog$Builder.setPositiveButton(AlertDialog.java:487)

当我注释掉下面一行时:

.setPositiveButton(DialogInterface.BUTTON_POSITIVE, null)

显示了对话框,但显然没有显示任何按钮。我需要在对话框中显示一个按钮!!

我做错了什么?

我认为 DialogInterface.BUTTON_POSITIVE 有问题 您可以在 here

找到解决方案

DialogInterface.BUTTON_POSITIVE 是常量,如果勾选 DialogInterface class:

int BUTTON_POSITIVE = -1;

setPositiveButton 方法收到一个 textId 或一个字符序列作为其参数,这是将出现在肯定按钮上的文本。 Android 找不到 DialogInterface 定义的 -1 id 的关联字符串。

我建议您在 xml 文件中定义正面按钮文本,就像您对标题和消息的标签所做的那样,并将其用于第一个参数。

相应地使用它

  AlertDialog.Builder alertbox = new AlertDialog.Builder(YourActivity.this);

               alertbox.setTitle("Do you want To exit ?");
               alertbox.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface arg0, int arg1) { 
                      // finish used for destroyed activity
                       exit();
                   }
               });

               alertbox.setNegativeButton("No", new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface arg0, int arg1) {
                           // Nothing will be happened when clicked on no button 
                           // of Dialog     
                 }
               });

               alertbox.show();
private void createAlertDialog() {

     AlertDialog.Builder alrtDialog = new AlertDialog.Builder(
                this);
        alrtDialog.setMessage("your message").setCancelable(false);
        alrtDialog.setPositiveButton("ButtonName",
                new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //Do somthing
            }
        });

        alrtDialog.setNeutralButton(R.string.cancel,
                new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                //Do somthing
            }
        });
        alrtDialog.create();
        alrtDialog.show();
    }

您需要像这样获取字符串 ID。

new AlertDialog.Builder(this)
    .setTitle(getResources().getString(R.string.label_searching))
    .setMessage(getResources().getString(R.string.label_search_noresults))
    .setCancelable(false)
    .setPositiveButton(DialogInterface.BUTTON_POSITIVE, null)
    .create().show();