2

我正在开发一个示例 android 应用程序,它在警报对话框中显示数字(1 到 5),并且数字在一秒钟后发生变化。现在我想在 5 秒后关闭 AlertDialog。我如何关闭警报对话框。你可以查看我到目前为止开发的代码。请在这方面帮助我。我将非常感谢帮助。

    timeView = new TextView(this);

    AlertDialog.Builder builder = new AlertDialog.Builder(this);


            builder.setView(timeView);
            builder.setTitle("Time"); 
            builder.setCancelable(false);
            builder.show();




timeView.postDelayed(new Runnable()
        {
            public void run()

            {

                switch(timeSecond)
                {

                     case 0:timeView.setText("5"); 
                     timeSecond++;
                     break;

                     case 1:timeView.setText("4"); 
                     timeSecond++;
                     break;

                     case 2:timeView.setText("3"); 
                     timeSecond++;
                     break;

                     case 3:timeView.setText("2"); 
                     timeSecond++;
                     break;

                     case 4:timeView.setText("1"); 
                     timeSecond++;
                     break;


                }
                if(timeSecond!=5)
                {
                    timeView.postDelayed(this,1000);

                }

                else
                {
                    //Here I want to close the Alert Dialog

                }

            }
        }, 1000);
4

2 回答 2

2
final AlertDialog dialog = builder.show();
....
dialog.dismiss() 

将关闭对话框。

编辑:对于上面的代码,我建议替代方案:

    if (!conditionTrue) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        builder.setTitle("Hello"); 
        builder.setMessage("Hello Android");
        builder.setCancelable(false);
        builder.show();
    }

如果您想关闭它,则无需显示对话框。

于 2012-10-08T16:33:06.780 回答
0

您不能将其分配给参考并对其调用驳回吗?

AlertDialog.Builder builder = new AlertDialog.Builder(this);

builder.setTitle("Hello"); 
builder.setMessage("Hello Android");
builder.setCancelable(false);
AlertDialog dialog = builder.show();
...
if(conditionTrue)
{
    //Here close the Alert Dialog
    dialog.dismiss()
}
于 2012-10-08T16:56:07.223 回答