避免显示两个警告对话框

时间:2014-11-07 05:16:53

标签: android

我正在尝试在我的Android应用中添加警告对话框。它工作正常,但问题是在对话框显示后,我点击主按钮它显示两个对话框一个唯一的标题,另一个是标题与消息内容和2个按钮。这是我的代码:

AlertDialog.Builder alertDialog = new AlertDialog.Builder(BuyFull.this);
alertDialog.setTitle(R.string.app_name);
alertDialog.setMessage(R.string.sms);    
alertDialog.setPositiveButton(R.string.buy, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
    Toast.makeText(getApplicationContext(), "You clicked on buy",    
Toast.LENGTH_SHORT).show();
}
});

alertDialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
    Toast.makeText(getApplicationContext(), "You clicked on NO", 
Toast.LENGTH_SHORT).show();
    dialog.cancel();
}
});

alertDialog.show();

2 个答案:

答案 0 :(得分:0)

AlertDialog.Builder alertDialog = new AlertDialog.Builder(BuyFull.this);
alertDialog.setTitle(R.string.app_name);
alertDialog.setMessage(R.string.sms);    
alertDialog.setPositiveButton(R.string.buy, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Toast.makeText(getApplicationContext(), "You clicked on buy",    
Toast.LENGTH_SHORT).show();
}
});

alertDialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "You clicked on NO", 
Toast.LENGTH_SHORT).show();
dialog.cancel();
}
});
AlertDialog dialog = alertDialog.create();
dialog.show()

答案 1 :(得分:0)

您需要在显示之前先创建对话框。只需在显示对话框之前添加一行,它就会像这样工作。

AlertDialog.Builder alertDialog = new AlertDialog.Builder(BuyFull.this);
alertDialog.setTitle(R.string.app_name);
alertDialog.setMessage(R.string.sms);    
alertDialog.setPositiveButton(R.string.buy, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Toast.makeText(getApplicationContext(), "You clicked on buy",    
Toast.LENGTH_SHORT).show();
}
});

alertDialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "You clicked on NO", 
Toast.LENGTH_SHORT).show();
dialog.cancel();
}
});
AlertDialog dialog = alertDialog.create();
dialog.show()