为什么AlertDiolog.show()会在Android中产生错误?
我正在尝试构建一个非常简单的警报对话框过程。我构建了这个对话框,这样它所做的唯一事情就是显示警报。但它却产生了一个错误 以下是我的项目的相关代码:为什么AlertDiolog.show()会在Android中产生错误?,android,android-alertdialog,Android,Android Alertdialog,我正在尝试构建一个非常简单的警报对话框过程。我构建了这个对话框,这样它所做的唯一事情就是显示警报。但它却产生了一个错误 以下是我的项目的相关代码: Button button = (Button)findViewById(R.id.btnCancel); button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Context appContext = getApplica
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的结果,也许 在创建对话框、祝酒词等时,不要使用应用程序上下文,而是使用活动上下文
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()即可)。
顺便说一句,AlertDialog.Builder是一个生成器,意味着您可以实际使用生成器模式;-)
有一篇关于何时使用哪个上下文的优秀文章:前面的答案是正确的,我认为在您的情况下,最好使用dialog.dismise()而不是dialog.cancel()。。但我认为这是一个背景问题。。尝试一个全球性的