How to prevent a AlertDialog from closing when a button is clicked

prevent a AlertDialog from closing when a button is clicked
You can prevent a AlertDialog from closing when a button is clicked.

It’s very easy you just need to use the following code in your application:

final AlertDialog dialog = new AlertDialog.Builder(context)
        .setView(v)
        .setTitle(R.string.my_title)
        .setPositiveButton(android.R.string.ok, null) //Set to null. We override the onclick
        .setNegativeButton(android.R.string.cancel, null)
        .create();

dialog.setOnShowListener(new DialogInterface.OnShowListener() {

    @Override
    public void onShow(DialogInterface dialog) {

        Button b = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
        b.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                // TODO Do something

            }
        });
    }
});

7 thoughts on “How to prevent a AlertDialog from closing when a button is clicked

  1. Line #13 needs to be

    Button b = ((AlertDialog)dialog).getButton(AlertDialog.BUTTON_POSITIVE);

    Otherwise great solution!

  2. Great solution, thanks!!, if someone need it in kotlin, that’s the code:

    val dialog = AlertDialog.Builder(activity!!)
    .setTitle(“Cambiar clave”)
    .setView(dialogView)
    .setCancelable(false)
    .setPositiveButton(“Aceptar”, null)
    .setNegativeButton(“Cancelar”, null)
    .create()

    dialog.setOnShowListener { _ ->
    val b = dialog.getButton(AlertDialog.BUTTON_POSITIVE)
    b.setOnClickListener {

    Toast.makeText(activity!!, “Funciona!!”, Toast.LENGTH_SHORT).show()
    }
    }
    dialog.show()

Leave a Reply

Your email address will not be published. Required fields are marked *