Reputation: 93
I want to open a dialog. And dismiss automatically after a few seconds, the button in the dialog should also dismiss a dialog, whatever happens first. But I can't find the right way to close the dialog after time is up
I use the next custom dialog
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();
}
The dialog XML is very simple, it just shows a title, message, and button.
I've been through this for a couple of days and can't figure out how to solve it.
Upvotes: 4
Views: 1963
Reputation: 888
You could also use Kotlin Coroutine:
'build your dialog...'
dialog.setOnShowListener {
CoroutineScope(Dispatchers.Main).launch {
delay(length)
dialog.dismiss()
}
}
dialog.show()
Where 'length' is the time in milliseconds that you want the dialog to show for.
Upvotes: 4
Reputation: 9912
You can try to add Handler:
dialogo.show();
final Handler handler = new Handler();
handler.postDelayed(new Runnable()
{
@Override
public void run()
{
// Close dialog after 1000ms
dialogo.cancel();
}
}, 1000);
After 1000 ms (1 sec) Your dialog will be closed. I think that You don't have to check if a dialog was closed with a button and when You call again close
on closed dialog You won't get any error but if I am not right just add a boolean variable to control if a dialog was closed by a button.
Upvotes: 5