警报对话框无法正常工作 - android

时间:2015-02-20 01:37:45

标签: java android button alert

我正在使用警告对话框询问用户确认数组的项目添加。我在警告对话框之前和之后打印数组大小,似乎两个打印都在警报对话框出现之前完成。

Log.d("before", ""+wayPoints.length);
AlertDialog.Builder ab = new AlertDialog.Builder(getContext());
ab .setTitle("Add entry");
ab .setMessage("Are you sure you want to add this entry?");
ab  .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() 
{
      public void onClick(DialogInterface dialog, int which) 
    {wayPoints = ArrayHandler.addAtIndex(wayPoints, node, 1);}
});
ab .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) { 
                        // do nothing
                    }
                 });
ab.setIcon(android.R.drawable.ic_dialog_alert);
ab.show();
Log.d("after", ""+wayPoints.length);

ArrayHandler.addAtIndex方法处理向提供的数组添加新项目。 问题是它是在警报对话框出现之前打印两个日志记录行。我需要在打印第二个日志之前完成警告对话框。

3 个答案:

答案 0 :(得分:1)

正确行为。在关闭对话框之前,show方法不会等待或阻止。在显示对话框后立即在show方法后继续执行代码。 (实际上,对话框甚至还没有显示 - 在你产生控制权后会发生这种情况。)

您已拥有setPositiveButtonsetNegativeButton处理程序,只需在用户按下按钮时将要执行的代码放在这些处理程序中。

如果您希望在对话框关闭时运行某些代码,无论点击哪个按钮,请使用setOnDismissListener将代码放在那里

答案 1 :(得分:-1)

使用:

AlertDialog alert1 =  ab.create();
alert.show();

而不是:

ab.show();

答案 2 :(得分:-1)

试试这个

AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(               context);  
            // set title        
    alertDialogBuilder.setTitle("Your Title"); 
            // set dialog message   
        alertDialogBuilder              .setMessage("Click yes to exit!")               .setCancelable(false)               .setPositiveButton("Yes",new DialogInterface.OnClickListener() {    
                public void onClick(DialogInterface dialog,int id) {        
                // if this button is clicked, close             
            // current activity             
            MainActivity.this.finish();                     }           
     })                 .setNegativeButton("No",new DialogInterface.OnClickListener() { 
                public void onClick(DialogInterface dialog,int id) {        
                // if this button is clicked, just close            
            // the dialog box and do nothing            
            dialog.cancel();        
            }       

.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
 public void onClick(DialogInterface dialog, int which) {
wayPoints = ArrayHandler.addAtIndex(wayPoints, node, 1);

Log.d("after", ""+wayPoints.length);
} });   
    });         
            // create alert dialog      
            AlertDialog alertDialog = alertDialogBuilder.create();  
                    // show it  
                alertDialog.show();
相关问题