Android:在警告对话框中添加延迟

6

我遇到了这样的问题,需要在几秒钟后弹出一个警告对话框。我尝试使用 postDelayed() 函数与 Handler 一起使用,但是没有成功。

new Handler().postDelayed(new
Runnable() {
        @Override
        public void run() {
          AlertDialog.Builder builder = new     AlertDialog.Builder(
                        MyActivity.this);
                builder.setTitle("My title...    ");
                builder.    setMessage("my msg..");
                builder.     setPositiveButton("OK",
                         new     DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                int     which) {
                            Log.    e("info", "OK");
                            }
                        });

                builder.show();
        }
    });
        }
}, 33000); 

如果它可以工作,或者无法工作,您需要等待33秒钟。 - Blackbelt
我已经尝试了,即使40秒过去了,警告对话框仍未弹出。 - Emm Jay
你可以尝试使用 Thread.sleep()。 - zgc7009
3个回答

8
您需要在builder.show()下方添加以下代码。这对我很有效。
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
    public void run() {
        dialog.dismiss();
    }   
}, 1500);  // 1500 seconds

编辑:

我以不同的方式使用这个功能,可以看到你的情况与我的不同。下面是我的完整代码。在我的情况下,我只想出现一个“模拟”进度对话框,并在一段时间后使其消失。

protected void ActiveProgressDialog() {
    final ProgressDialog dialog = ProgressDialog.show(getActivity(), "", getResources().getString(R.string.carregantInfo), true);
    dialog.show();
    Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        public void run() {
            dialog.dismiss();
        }   
    }, 1500);  // 1500 milliseconds
}

}

抱歉!我不明白你的意思,请您能否详细说明一下? - Emm Jay
抱歉之前我没有理解你的意思。我明白你想要的是相反的。我会尝试找到一个解决方案。如果我找到什么,我会发布出来!抱歉。 - Joan Gil
我为您找到了答案。希望能对您有所帮助!:https://stackoverflow.com/questions/13652130/delay-an-alertdialog - Joan Gil

1
我知道这是一个老问题,但我认为问题可能在于您没有从主(UI)线程运行。请确保您的处理程序与主线程关联,使用以下方法:
new Handler(Looper.getMainLooper()).postDelayed(...);

希望这有所帮助!

0
private Thread mMainThread;

mMainThread = new Thread(){

        @Override
        public void run(){
            try{
                synchronized (this) {
                    wait(33);
                                try{

       AlertDialog.Builder builder = new     AlertDialog.Builder(
                    MyActivity.this);
            builder.setTitle("My title...    ");
            builder.    setMessage("my msg..");
            builder.     setPositiveButton("OK",
                     new     DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,
                            int     which) {
                        Log.    e("info", "OK");
                        }
                    });

            builder.show();
    }catch(Exception e){

    }
                }
            }catch (Exception e) {
            }
            }};

希望能有所帮助


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接