如何自动关闭自定义对话框

时间:2020-07-22 16:09:51

标签: java android android-alertdialog

我想打开一个对话框。几秒钟后自动关闭,对话框中的按钮也应该关闭对话框,无论先发生什么。但是我找不到在时间到后关闭对话框的正确方法

我使用下一个自定义对话框

private void okShowDialog(String title, String message){
    vibrate();
    final Dialog dialogo=new Dialog(Login.this);
    dialogo.setContentView(R.layout.okdialog);
    dialogo.setCancelable(false);
    TextView errorTitle=dialogo.findViewById(R.id.lblTitleDialog);
    errorTitle.setText(title);
    TextView errorMessage=dialogo.findViewById(R.id.txtErrorDialog);
    errorMessage.setText(message);
    Button dialogButton = (Button) dialogo.findViewById(R.id.btnCont);
    dialogButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onBackPressed();
        }
    });
    dialogo.show();
}

对话框XML非常简单,它仅显示标题,消息和按钮。

我已经经历了几天,却不知道如何解决。

2 个答案:

答案 0 :(得分:2)

您可以尝试添加处理程序:

dialogo.show();

final Handler handler = new Handler();
handler.postDelayed(new Runnable()
{
    @Override
    public void run()
    {
        // Close dialog after 1000ms
        dialogo.cancel();
    }
}, 1000);

1000毫秒(1秒)后,您的对话框将关闭。我认为您不必检查对话框是否已通过按钮关闭,并且当您在已关闭的对话框上再次调用close时,不会出现任何错误,但是如果我不正确,只需向其中添加一个布尔变量控制对话框是否被按钮关闭。

答案 1 :(得分:0)

您还可以使用Kotlin Coroutine:

'build your dialog...'
dialog.setOnShowListener {
    CoroutineScope(Dispatchers.Main).launch {
        delay(length)
        dialog.dismiss()
    }
}
dialog.show()

“长度”是您希望对话框显示的时间(以毫秒为单位)。