如何使AlertDialog阻止代码?

时间:2011-10-04 07:34:00

标签: android

我正在尝试使用确定按钮显示消息框。我为此目的使用AlertDialog,我意识到它没有阻止代码。例如:

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

       new AlertDialog.Builder(this).setTitle("Test dlg").setMessage("Alert 1")
        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {}
        })
        .setNegativeButton("", null)
        .show();

       new AlertDialog.Builder(this).setTitle("Test dlg").setMessage("Alert 2")
       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
           @Override
           public void onClick(DialogInterface dialog, int which) {}
       })
       .setNegativeButton("", null)
       .show();
        //...continue with UI initialization here...
    }

当我开始活动时,它会显示Alert2,当我按下确定后,它会显示Alert1。

我需要有阻止代码对话框,所以首先它应该显示Alert1消息,等到用户按下OK按钮然后继续执行代码并显示Alert2消息等。例如:

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
      msgBox("Test dlg", "Alert 1");
      msgBox("Test dlg", "Alert 2");
      //...continue with UI initialization here...
    }


private void msgBox(String title, String msg){

   //?????

   /*  WRONG, NON-BLOCKING
   new AlertDialog.Builder(this).setTitle(title).setMessage(msg)
        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {}
        })
        .setNegativeButton("", null)
        .show();
   */
}

我应该怎么写// ?????放在msgBox方法中?

更多示例,我需要这样的事情:

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
   if (isInitialisationDataFailed()){
      msgBox("Alert", "Cannot open activity, sorry");
      myActivity.this.finish();
      return;
    }
}

但这不起作用。活动结束比屏幕上显示的警报更快。

将消息框代码与自己的方法分开以使其可重用的主要思路。怎么做到这一点?

///////////////////////////////// 另一个例子:

private void init(){
  //init code here...
  if (isSomethingWhrong()){
    msgbox("wrong stuff will be fixed");
    //do fix wrong stuff here...
  }
  if (isAnotherthingWrong()){
    msgbox("more wrong stuff will be fixed");
    //do fix more wrong stuff....
  }
  //continue init code here...
}

private void msgbox(String msg){
    //BLOCKING DIALOG REALISATION here...
}

作为替代方案:

private void init(){
  //init code here...
  handleWrongStuff();
}
private void handleWrongStuff(){
 if (isSomethingWhrong()){
   new AlertDialog.Builder(activity)
        .setTitle("Test")
        .setMessage("wrong stuff will be fixed")
        .setPositiveButton("OK", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                 //do fix wrong stuff here...
                 handleMoreWrongStuff();       
            }

        })
        .setNegativeButton("", null)
        .show();
 }
  else{
     handleMoreWrongStuff();   
  }
}

private void handleMoreWrongStuff(){
 if (isAnotherthingWrong()){
   new AlertDialog.Builder(activity)
        .setTitle("Test")
        .setMessage("more wrong stuff will be fixed")
        .setPositiveButton("OK", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                 //do fix more wrong stuff here...    
                 continueInit();  
            }

        })
        .setNegativeButton("", null)
        .show();
 }
  else{
    continueInit();  
  }
}

private void continueInit(){
  //continue init code here...
}
你知道复杂性的差异吗?为了使init代码在Android中工作,我需要将它拆分为单独的方法,而不是逻辑块,但是当我需要显示对话框时。此外,重复初始化对话框的代码变得丑陋且难以理解。

8 个答案:

答案 0 :(得分:4)

将代码显示在第一个警告对话框的onClick of Positive按钮上显示第二个对话框。

答案 1 :(得分:2)

使用这种方式你不能停止执行但是你可以把它放在按钮动作监听器上,这样当那时按下按钮时会调用监听器并且你可以执行例如代码。在你的情况下,当你按下确定按钮然后显示来自听众的下一个警报。

    new AlertDialog.Builder(this).setTitle("Test dlg").setMessage("Alert 1")
    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
               new AlertDialog.Builder(YourActivity.this).setTitle("Test dlg").setMessage("Alert 2")
              .setPositiveButton("OK", new DialogInterface.OnClickListener() {
               @Override
               public void onClick(DialogInterface dialog, int which) {}
               })
             .setNegativeButton("", null)
             .show();
        }
    })
    .setNegativeButton("", null)
    .show();

答案 2 :(得分:1)

对话框不会阻止代码执行 - 非常简单。实现“块状”行为的唯一方法是将执行链分成较小的位。

让我们假设您希望在UI初始化期间显示总共五个对话框。在“活动”中,您将创建以下方法:

private void beforeFirstDialog() {
   // Do the initialization until you want the first dialog
   // Show the first dialog
   // When clicking 'OK' in the first dialog, beforeSecondDialog() is called.
}

private void beforeSecondDialog() {
   // Do the initialization until you want the second dialog
   // Show the second dialog
   // When clicking 'OK' in the second dialog, beforeThirdDialog() is called.
}

private void beforeThirdDialog() {
   // Do the initialization until you want the third dialog
   // Show the third dialog
   // When clicking 'OK' in the third dialog, beforeFourthDialog() is called.
}

private void beforeFourthDialog() {
   // Do the initialization until you want the fourth dialog
   // Show the fourth dialog
   // When clicking 'OK' in the first dialog, beforeFifthDialog() is called.
}

private void beforeFifthDialog() {
   // Do the initialization until you want the fifth dialog
   // Show the fifth dialog
   // When clicking 'OK' in the first dialog, afterFifthDialog() is called.
}

private void afterFifthDialog() {
   // Do what needs to be done after the last dialog.
}

答案 3 :(得分:1)

这是一个迟到的答案,但可能会让你闭幕。

执行所需操作的最简洁方法是启动活动,而不是对话框简单活动只需一个OK按钮。

按下确定按钮后,只需关闭活动即可 如果您需要更复杂的响应,更多按钮,文本输入等。
使用 StartActivityWithResult()返回用户的选择

答案 4 :(得分:0)

在条件下给出了这个。

ShowAlert.displayAlert(现在的班级名称。这,“请输入错误信息”);

          strDomain.requestFocus();

创建一个新的ShowAlert类,里面放了这段代码。

公共类ShowAlert {

    public static void displayAlert(Activity act,String msg)
    {
        AlertDialog.Builder alert = new AlertDialog.Builder(act);
        alert.setMessage(msg).setPositiveButton("OK", new DialogInterface.OnClickListener(){
             @Override
             public void onClick(DialogInterface dialog, int which)
             {   

             }
             })
             .show();
    }

}

答案 5 :(得分:0)

EditText strDomain;

strDomain是edittext名称。 它就像当该字段为null时我已经使它像它被填充它不会进入下一页..当你想在想要的实例显示消息时你的情况是什么?

答案 6 :(得分:0)

正如您(可能)从许多回复中发现的那样,您不应该阻止Main UI Thread。但是,如果您有充分的理由在获得响应时阻止代码 从用户那里,您可以创建一个线程,在AlertDialog MainUI显示Thread的同时循环/等待用户输入。我有full blog post here解释了这个

protected void RunConfirmAction(Action runnableAction)
{
    var confirmThread = new Thread(() => runnableAction());
    confirmThread.Start();
}

// OnClick (when the user clicks Logout Button, I call this
RunConfirmAction(Logout);

// the implemtation of the MessageBox waiting looks like this:
public DialogResult MessageBoxShow(string message, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton)
{
    if (_CurrentContext != null && MainActivity != null)
    {
        Action<bool> callback = OnConfirmCallBack;
        _IsCurrentlyInConfirmProcess = true;
        Action messageBoxDelegate = () => MessageBox.Show(((Activity)MainActivity), callback, message, caption, buttons);
        RunOnMainUiThread(messageBoxDelegate);
        while (_IsCurrentlyInConfirmProcess)
        {
            Thread.Sleep(1000);
        }               
    }
    return _ConfirmBoxResult ? DialogResult.OK : DialogResult.No;
}

private void OnConfirmCallBack(bool confirmResult)
{
    _ConfirmBoxResult = confirmResult;
    _IsCurrentlyInConfirmProcess = false;
}

private bool _ConfirmBoxResult = false;
private bool _IsCurrentlyInConfirmProcess = false;

我希望这可以帮助某人,解决方案的全部细节可以是found here

答案 7 :(得分:0)

Kotlin使生活变得轻松,可以在例程中调用

suspendCoroutine<Context> { cont ->
     runOnUiThread {
            val builder = androidx.appcompat.app.AlertDialog.Builder(this@YourScreen)
            builder.setTitle("Title")
            builder.setMessage("I have a message for you")
            builder.setPositiveButton("Yes") { _, _ ->
                   /* Do something on yes */
            }
            builder.setNegativeButton("No") { _, _ ->
                   /* Do something on no */
            }
            builder.setOnCancelListener {
                  cont.resume(this@YourScreen)
            }
            val askdialog = builder.create()
            askdialog.show()
     }
}
//Code will continue here