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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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
 
            }
        });
    }
});