0

I create multi choice dialog using AlertDialog.Buiilder

        mDialog =    new AlertDialog.Builder(getActivity()).setIconAttribute(mIcon).setTitle(mTitle)
            .setPositiveButton(mPositiveButton, new OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    mCallbacks.onPositiveClick(((AlertDialog) getDialog()).getListView().getCheckedItemPositions(), mChoices);
                }
            }).setNegativeButton(mNegativeButton, new OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    mCallbacks.onNegativeClick(((AlertDialog) getDialog()).getListView().getCheckedItemPositions());
                }
            }).setMultiChoiceItems(mChoices, mCheckedItems, new OnMultiChoiceClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                    if (mIsCheckedRequired) {
                        AlertDialog alertDialog = ((AlertDialog) dialog);

                        if (alertDialog.getListView().getCheckedItemCount() == 0)
                            alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
                        else
                            alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(true);
                    }

                }
            }).create();

Also I want to make positive button disabled when no items checked:

    @Override
public void onStart() {
    super.onStart();
    if (mIsCheckedRequired && mDialog.getListView().getCheckedItemCount() == 0) {
        mDialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
    }
}

mDialog.getListView().getCheckedItemCount() always retruns 0 before click, is there a way to know the checked items count before click except having field mCheckedItems array and running through it?

Vahan
  • 3,016
  • 3
  • 27
  • 43

1 Answers1

1

For this better to manage a class level counter. and on every onClick of OnMultiChoiceClickListener just re-initialize it size as per item count. And don't forget to initialize it by 0 whenever you are showing the dialog. And you can also check if your counter is zero then don't process the ok button click.

Hope it will help you :)

Neo
  • 3,546
  • 1
  • 24
  • 31
  • Thanks, I know that solution) Can you explain me why for example ((AlertDialog) getDialog()).getListView().getCheckedItemPositions() correctly works for example in positive button click but don't work in onCreateDialog() or onStart() ? – Vahan Aug 03 '16 at 08:42