0

我正在尝试构建一个非常简单的警报对话过程。我构建了对话框,因此它唯一要做的就是显示警报。但它反而会产生错误。

这是我的项目的相关代码:

Button button = (Button)findViewById(R.id.btnCancel);
button.setOnClickListener(new View.OnClickListener() {
  public void onClick(View v) {
    Context appContext = getApplicationContext();                                   
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(appContext);                
    alertDialogBuilder.setTitle("Your Title");
    alertDialogBuilder
        .setMessage("Click yes to exit!")
        .setCancelable(false)
        .setPositiveButton("Yes",new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog,int id) {
            try {
              HttpResponse response=RestServicesCaller.cancelTransaction(transactionId);
            } catch (JSONException e) {
              e.printStackTrace();
            } catch (IOException e) {
              e.printStackTrace();
            }
          }
        })
        .setNegativeButton("No",new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog,int id) {
            dialog.cancel();
          }
        });

    AlertDialog alertDialog = alertDialogBuilder.create();
    alertDialog.show();

alertDialog.show()如果我在按下按钮时注释掉,什么都不会发生(如预期的那样)。但是如果我按下按钮打开它,它会强制关闭程序。什么会导致这种情况?

我认为这可能是 xml 的结果...?

4

2 回答 2

1

在创建对话框、toast 等时不要使用应用程序上下文,而是使用活动上下文。

Button button = (Button)findViewById(R.id.btnCancel);
button.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        new AlertDialog.Builder(MyActivity.this)
            .setTitle("Your Title")
            .setMessage("Click yes to exit!")
            .setCancelable(false)
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                 public void onClick(DialogInterface dialog,int id) {
                    try {
                        HttpResponse response = RestServicesCaller.cancelTransaction(transactionId);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                 }
             })
             .setNegativeButton("No",new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog,int id) {
                    dialog.cancel();
                }
             })
             .show();
    }
});

MyActivity 将是您的活动(如果它是一个片段,只需使用 getActivity() 代替)。BTW AlertDialog.Builder 是一个构建器,这意味着您实际上可以使用构建器模式;-)。

有一篇关于何时使用哪个上下文的优秀文章:http: //www.doubleencore.com/2013/06/context/

于 2013-07-30T22:13:50.193 回答
0

以前的答案是正确的https://stackoverflow.com/a/17958395/1326308我认为在你的情况下最好使用dialog.dismiss()而不是dialog.cancel()

于 2013-07-30T22:32:58.713 回答