Android对话框显示另一个带有thread.sleep的对话框

时间:2014-06-01 18:33:12

标签: android dialog thread-sleep

我有一个启动对话框的活动。 该对话框包含一个按钮,该按钮显示与thread.sleep(4000)完全不同的对话框。 但是第二个对话框没有显示出来。 我的代码:

public boolean onCreateOptionsMenu(Menu menu) {


    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.screen_center, menu);
    Button btnAssign = (Button)findViewById(R.id.btnAssigDataCent);
    btnAssign.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            final Dialog dialog = new Dialog(ScreenCentCon.this);

            dialog.setContentView(R.layout.dialogassign1);
            dialog.setTitle("Choose option");
            Button btnAssign = (Button) dialog.findViewById(R.id.btnDialogCenterAssign);
            btnAssign.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    dialog.dismiss();

                    final Dialog dialog2 = new Dialog(ScreenCentCon.this);
                    dialog2.setContentView(R.layout.dialogassign2);
                    dialog2.setTitle("Wait");

                    dialog2.show();
                    try {
                        synchronized (this) {
                            Thread.sleep(4000);
                            dialog2.dismiss();
                        }

                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }                   
                }
            });
            dialog.show();
        }
    });

}

代码仅显示第一个对话框,但等待4秒以解除活动。

1 个答案:

答案 0 :(得分:4)

Thread.sleep()将完全阻止UI线程,从而阻止对话甚至被绘制。一般来说,这是一个非常糟糕的主意。

如果要显示对话框4秒钟然后自动关闭它,则应使用Handler.postDelayed()。类似的东西:

mHandler = new Handler();

...

dialog2.show();
mHandler.postDelayed(new Runnable()
{
    @Override
    public void run() {
        dialog2.dismiss();
    } 
}, 4000);