Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to close a custom dialog automatically

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.

like image 845
Marco Espinoza Avatar asked Oct 27 '25 07:10

Marco Espinoza


1 Answers

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.

like image 133
iknow Avatar answered Oct 28 '25 21:10

iknow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!