Search code examples
androidlistviewandroid-dialogfragment

Android: Listen to PositiveButton click in custom DialogFragment


I am creating a custom AlertDialog to get a list of items like this...

Dialog Fragment:

public class MultiListDialog extends DialogFragment {
    private ArrayList<Integer> selectedItems = new ArrayList<>();

    public MultiListDialog newInstance(Bundle args) {
        MultiListDialog d = new MultiListDialog();
        d.setArguments(args);
        return d;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        selectedItems = new ArrayList();
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

        builder.setTitle(getArguments().getString("title", ""))
                .setMultiChoiceItems(getArguments().getCharSequenceArray("list"), null, new DialogInterface.OnMultiChoiceClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                                if (isChecked) {
                                    selectedItems.add(which);
                                } else if (selectedItems.contains(which)) {
                                    selectedItems.remove(Integer.valueOf(which));
                                }
                            }
                        })
                .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int i) {

                    }
                })
                .setNegativeButton(R.string.cancel_only, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int i) {
                        dialog.cancel();
                    }
                });

        return builder.create();
    }


    public ArrayList<String> getSelectedItems() {
        ArrayList<String> ret = new ArrayList<>();
        for (int i=0; i<selectedItems.size(); i++)
            ret.add(getArguments().getCharSequenceArray("list")[i].toString());

        return ret;
    }
}

Activity:

Bundle args = new Bundle();
                        args.putString("title", "My Title");
                        args.putCharSequenceArray("list", arrayList.toArray(new CharSequence[arrayList.size()]));

                        DialogFragment fragment = new MultiListDialog().newInstance(args);
                        fragment.show(getFragmentManager(), "my_frag");

How can I go about retrieving the selected items on OK click? I tried add interfaces and abstract functions, but was not able to get it working properly.


Solution

  • It's ok to use DialogFragment#getActivity() method and to cast it to your listening interface. Also you can pass your activity as a listener to your dialog fragment and null it within onDestroy()