简体   繁体   中英

Alert Dialog does not dismiss

In the below code snippet alertdialog.dismiss is not working don't know why. Logs work fine but the dialog does not dismiss. override fun onReceive(context: Context, arg1: Intent) {

        var builder = AlertDialog.Builder(context)
                .setTitle("Network Error !")
                .setMessage("Check your internet connection...")
                .setCancelable(false)
        var alertDialog:AlertDialog = builder.create()

            if (isConnectedOrConnecting(context)) {
                    alertDialog.dismiss()
                    Log.i("Network","Alive")

            } else{
                Log.i("Network","Dead")
                alertDialog.show()
                //alertDialog.dismiss()
            }
    }

Problem Solved.

Initialize the builder.create in the place where we call alert.show

var alertDialog:AlertDialog? = null
override fun onReceive(context: Context, arg1: Intent) {
    var dialogBuilder = AlertDialog.Builder(context).setTitle("Network Error !")
            .setCancelable(false)
            .setMessage("Check your internet connection...")

    if (isConnectedOrConnecting(context)) {
        //initializeDialog(context)
        alertDialog!!.dismiss()
        Log.i("Network","Alive")
    }else{
        alertDialog = dialogBuilder.create()
        alertDialog!!.show()
        Log.i("Network","Dead")
        //initializeDialog(context).create()
    }
}

You should be able to use either Dialog.dismiss(), or Dialog.cancel()

alertDialog.setNeutralButton("OK", new DialogInterface.OnClickListener() { // define the 'Cancel' button
    public void onClick(DialogInterface dialog, int which) {
        //Either of the following two lines should work.
        dialog.cancel();
        //dialog.dismiss();
    } 
});

Otherwise you can dismiss your dialog after few seconds

final AlertDialog.Builder dialog = new AlertDialog.Builder(this).setTitle("Leaving launcher").setMessage("Are you sure you want to leave the launcher?");
dialog.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int whichButton) {
        exitLauncher();
    }
});     
final AlertDialog alert = dialog.create();
alert.show();

// Hide after some seconds
final Handler handler  = new Handler();
final Runnable runnable = new Runnable() {
    @Override
    public void run() {
        if (alert.isShowing()) {
            alert.dismiss();
        }
    }
};

alert.setOnDismissListener(new DialogInterface.OnDismissListener() {
    @Override
    public void onDismiss(DialogInterface dialog) {
        handler.removeCallbacks(runnable);
    }
});

handler.postDelayed(runnable, 10000)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM