在 Multichoice AlertDialog 中更改预定义项目的值
Posted
技术标签:
【中文标题】在 Multichoice AlertDialog 中更改预定义项目的值【英文标题】:Change values of predefined Items in Multichoice AlertDialog 【发布时间】:2021-09-23 19:02:06 【问题描述】:我一直在尝试实现一个多选警报对话框,在大多数情况下,一切都清晰易懂,但警报对话框从布尔数组中获取项目的状态,并且所有项目都设置为真。如果在警报对话框中选中它,我无法弄清楚如何更改数组中某个项目的状态。
private void showCategorySelectionDialog()
// Prepare the dialog by setting up a Builder.
final String selectionTitle = "Show on map: ";
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(selectionTitle);
final String[] categories = new String[]"Camping grounds","Abandoned places","Nature areas","Lookout Points";
// Find the current map type to pre-check the item representing the current state.
boolean[] checkedItems = new boolean[]
true,
true,
true,
true
;
// Add an OnClickListener to the dialog, so that the selection will be handled.
builder.setMultiChoiceItems(
categories,
checkedItems,
new DialogInterface.OnMultiChoiceClickListener()
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked)
//check which item is clicked and if it was true then set it as false.
if (isChecked && checkedItems[which] == true)
checkedItems[which]= false;
else
//If item was clicked and the value was false then set it as true.
checkedItems[which] = true;
);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener()
@Override
public void onClick(DialogInterface dialog, int which)
dialog.dismiss();
);
// Build the dialog and show it.
AlertDialog categoryDialog = builder.create();
categoryDialog.setCanceledOnTouchOutside(true);
categoryDialog.show();
当前的解决方案不会改变值,我的假设是我以不正确的方式处理数组,但我不确定正确的方式会是怎样。
【问题讨论】:
【参考方案1】:由于您希望在检查时更改数组中某个元素的值,因此您可以尝试将该值设置为与通过onClick()
方法传递的isChecked
变量相等。
检查下面的代码:
// Add an OnClickListener to the dialog, so that the selection will be handled.
builder.setMultiChoiceItems(
categories,
checkedItems,
new DialogInterface.OnMultiChoiceClickListener()
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked)
checkedItems[which] = isChecked;
);
【讨论】:
以上是关于在 Multichoice AlertDialog 中更改预定义项目的值的主要内容,如果未能解决你的问题,请参考以下文章
如何在 Flutter 中将 AlertDialog FlatButton 居中