Scott Ferguson
Scott Ferguson

Reputation: 7830

Prevent dialog containing a list from dismissing upon selection

I have a Dialog Fragment that contains a list of items. By default when you touch an item, the dialog dismiss. How can I prevent the dismiss at this point? (I want to programmatically dismiss the dialog at a later stage)

I am following the code sample as directed from here: https://developer.android.com/guide/topics/ui/dialogs.html

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setTitle(R.string.pick_color)
           .setItems(R.array.colors_array, new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int which) {
           }
    });
    return builder.create();
}

I see there is an option to use builder.setSingleChoiceItems instead of builder.setItems(), which will give me the behavior I desire, but not the style. (It comes with radio buttons, which I don't want)

Upvotes: 3

Views: 812

Answers (2)

Multi
Multi

Reputation: 51

Set a listener on the ListView after the dialog has been created, like this:

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {

    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    final AlertDialog dialog = builder.setTitle("My dialog")
            .setItems(new String[]{"Do nothing...", "Dismiss!"}, null) // any listener will do!
            .create();

    // add this listener after dialog creation to stop auto dismiss on selection
    AdapterView.OnItemClickListener listener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            switch(position) {
                case 0:
                    // do nothing selected
                    break;
                case 1:
                    // dismiss selected
                    dialog.dismiss();
                    break;
            }
        }
    };
    dialog.getListView().setOnItemClickListener(listener);
    return dialog;
}

Upvotes: 5

Lino
Lino

Reputation: 6160

I think you should use DialogFragment's setItems, providing the items but instead of providing an instance of the onClickListener, just provide null. Namely:

.setItems(R.array.colors_array, null);

You can dismiss later the dialog as you wish.

Upvotes: 0

Related Questions