如何在AlertDialog multiChoiceItems中获取所有选定的索引

thu*_*nja 3 android list listener android-alertdialog

我试图解决这个问题时遇到了一些麻烦.我所拥有的是一个多选机警报对话框,我想要做的是当按下正按钮时,我想要在已检查的索引上执行任务.我该怎么做呢?

这就是我要做的......

dialog.setMultiChoiceItems(list, null, null);
dialog.setPositiveButton("Okay", null);
Run Code Online (Sandbox Code Playgroud)

摘要:如何从AlertDialog获取所有已检查的索引?

ste*_*las 8

我采用的方法是声明a final Boolean []来存储项目的状态,然后当我调用setMultiChoiceItems方法时,我提供了一个DialogInterface.OnMultiChoiceClickListener在更改时设置此数组中每个项目的状态.然后当单击正面按钮时,我可以从中引用此数组DialogInterface.OnClickListener.

例如(从我的一些代码中复制并稍微混淆):

    final int aIndex = 0;
    final int bIndex = 1;
    final int cIndex = 2;
    final int dIndex = 3;

    final CharSequence[] items = {
            context.getString(R.string.string_share_include_a),
            context.getString(R.string.string_share_include_b),
            context.getString(R.string.string_share_include_c),
            context.getString(R.string.string_share_include_d) };

    final Boolean[] state = new Boolean[4];
    state[aIndex] = true;
    state[bIndex] = true;
    state[cIndex] = true;
    state[dIndex] = false;

    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    builder.setTitle(R.string.string_share_dialog_title);
    builder.setMultiChoiceItems(items, new boolean[] { true, true, true,
            false }, new DialogInterface.OnMultiChoiceClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which,
                boolean isChecked) {
            state[which] = isChecked;
        }
    });

    builder.setPositiveButton(R.string.string_share_ok,
            new OnClickListener() {

                public void onClick(DialogInterface dialog, int which) {

                    Utilities.shareStuff(
                            state[aIndex],
                            state[bIndex],
                            state[cIndex],
                            state[dIndex]);
                }
            });
Run Code Online (Sandbox Code Playgroud)