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

时间:2011-07-27 16:10:46

标签: android list listener alertdialog

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

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

dialog.setMultiChoiceItems(list, null, null);
dialog.setPositiveButton("Okay", null);

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

1 个答案:

答案 0 :(得分:8)

我采用的方法是声明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]);
                }
            });