如何自动关闭自定义对话框
How to close a custom dialog automatically
我想打开一个对话框。并在几秒钟后自动关闭,对话框中的按钮也应该关闭对话框,无论先发生什么。但是我找不到正确的方法在时间到后关闭对话框
我使用下一个自定义对话框
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 非常简单,它只显示标题、消息和按钮。
我已经经历了几天了,不知道如何解决。
您可以尝试添加Handler:
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
你不会得到任何错误,但如果我不正确,只需添加一个布尔变量到控制是否通过按钮关闭对话框。
您也可以使用 Kotlin 协程:
'build your dialog...'
dialog.setOnShowListener {
CoroutineScope(Dispatchers.Main).launch {
delay(length)
dialog.dismiss()
}
}
dialog.show()
其中 'length' 是您希望对话框显示的时间(以毫秒为单位)。
我想打开一个对话框。并在几秒钟后自动关闭,对话框中的按钮也应该关闭对话框,无论先发生什么。但是我找不到正确的方法在时间到后关闭对话框
我使用下一个自定义对话框
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 非常简单,它只显示标题、消息和按钮。
我已经经历了几天了,不知道如何解决。
您可以尝试添加Handler:
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
你不会得到任何错误,但如果我不正确,只需添加一个布尔变量到控制是否通过按钮关闭对话框。
您也可以使用 Kotlin 协程:
'build your dialog...'
dialog.setOnShowListener {
CoroutineScope(Dispatchers.Main).launch {
delay(length)
dialog.dismiss()
}
}
dialog.show()
其中 'length' 是您希望对话框显示的时间(以毫秒为单位)。