是否可以在列表中显示带有禁用项目(行)的多选警报对话框?
通过选中列表中的“无”选项,列表中的所有选项都应该被禁用,除了“无”选项,如果我取消选中“无”选项,需要再次启用所有项目吗?
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
dialogBuilder.setMultiChoiceItems(optionsList,selectionState,new
DialogInterface.OnMultiChoiceListener()
{
@Override
public void onClick(DialogInterface dialog,int which, boolean isChecked){
final AlertDialog alertDialog = (AlertDialog) dialog;
final ListView alertDialogList = alertDialog.getListView();
// Here how to make the items in the list as disabled when None is clicked
// None OPtion is one among in optionsList string array
// A loop to disable all items other than clicked one
for (int position = alertDialogList.getCheckedItemPosition(); position<
alertDialogList.getChildCount; position++)
{
alertDialogList.getChildAt(position).setEnabled(false);
}
}
});
最佳答案
您的 OnMultiChoiceClickListener
快到了。它只有两个问题:首先,您的 for
循环不会迭代所有子级,除了被点击的子级。
// A loop to disable all items other than clicked one
for (int position = alertDialogList.getCheckedItemPosition(); position<
alertDialogList.getChildCount; position++)
{
alertDialogList.getChildAt(position).setEnabled(false);
}
你从点击的那个开始,禁用那个,然后是它之后的所有 child ,直到列表的末尾。只有严格在点击之前的 child 才不会被禁用。第二个问题是您的禁用代码将针对单击的任何项目运行,而不仅仅是“无”项目。尝试这样的事情。我正在使用
which
来确定是否按下了特殊的“无”项。private static final int specialItem = ...;
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if (which == singleItem) { // only if they clicked 'none'
final AlertDialog alertDialog = (AlertDialog) dialog;
final ListView alertDialogList = alertDialog.getListView();
for (int position = 0; position < alertDialogList.getChildCount(); position++)
{
if (position != which) {
alertDialogList.getChildAt(position).setEnabled(!isChecked);
}
}
}
}
请注意,如果
which
不为 0,我什么都不做。我的 for
循环从 1 开始以避免项目 0,如果未选中“none”项目并禁用,它会将每个元素设置为启用如果检查了 none 项目。最后,我会注意到这不是多选对话框的常见行为。用户会对'none' 选项的行为感到惊讶,因为它与其他选项不同。没有“无”选项会更常见:如果用户不检查任何其他选项,则意味着没有。如果您确实需要一个“无”选项,要区分用户明确选择“无”和不回答之间的区别,请考虑使用带有单独的“无”按钮或复选框组之外的单选按钮的自定义布局,这样用户就可以知道它的行为会有所不同。
关于安卓 : Alert Dialog with Multi Choice,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12946119/