Question

I have a dialog with items:

final String[] items = new String[] { "item1", "item2" };

AlertDialog.Builder adb = new AlertDialog.Builder(this).setTitle("Title");
adb.setCancelable(false);
adb.setItems(items, new OnClickListener() {

    @Override
    public void onClick(DialogInterface d, int n) {
        Toast.makeText(MainActivity.this, items[n], Toast.LENGTH_LONG).show();
    });
}

AlertDialog alert = adb.create();
alert.setCancelable(false);
alert.show();

When a item is selected, the Toast is shown and the dialog closes. How can I disable this? I want that the dialog still remains open after a item is selected.

Was it helpful?

Solution 2

You are using AlertDialog.Builder.setItems() method which dismisses a dialog when an item is clicked.

In order to display a list of items and not have the dialog dismissed, you should use one of the overloads of setSingleChoiceItems() method:

Set a list of items to be displayed in the dialog as the content, you will be notified of the selected item via the supplied listener. The list will have a check mark displayed to the right of the text for the checked item. Clicking on an item in the list will not dismiss the dialog. Clicking on a button will dismiss the dialog.

OTHER TIPS

Set the second parameter in the setItems method to null and attach an item listener to the listview that is part of the dialog:

var alertDialog: AlertDialog? = null
val builder = AlertDialog.Builder(context!!, R.style.alertDialogTheme)
    .setItems(items.toTypedArray(), null)
    .setTitle("My Dialog Title")
    .setPositiveButton(
        "OK"
    ) { dialog, id ->
        dialog.dismiss()
    }.setNegativeButton(
        "Cancel"
    ) { dialog, id ->
        dialog.dismiss()
    }

alertDialog = builder.show()
alertDialog.listView.setOnItemClickListener(object: AdapterView.OnItemClickListener {
    override fun onItemClick(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {
        // Do something with item click.
    }
})
alertDialog.setCancelable(false)

There are two methods I use. The first one is the easiest, The second one is the same as the above @AndroidDev's answer.

First One

builder.setItems(items, (dialogInterface, n) -> {
        if(n == 0){
            builder.show();
            Toast.makeText(MainActivity.this, items[n], Toast.LENGTH_LONG).show();
        }
    });

Second One: (Same as the above one but here as the Java8 lambda)

AlertDialog dialog = builder.create();
    dialog.getListView().setOnItemClickListener((adapterView, subview, i, l)->{

    });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top