Reputation: 305
I have been trying to implement a multichoice alertdialog and for the most part everything is clear and understandable but the alertdialog gets the state of the items from a boolean array and all the items are set as true. I can't quite work out how I could change the state of an item in the array if it is checked in the alertdialog.
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();
}
This current solution does not change values and my assumptions are that I am handling the Array in an incorrect way but I am not sure how the right way would be.
Upvotes: 0
Views: 48
Reputation: 176
Since you want to change the value for an element in the array when it was checked then you can try to set the value to be equal with the isChecked
variable that is passed through onClick()
method.
Check the code below:
// 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;
}
}
);
Upvotes: 1