我从服务器获得List
,我在MultiChoice AlertDialog
中显示为字段。当用户检查字段时,我将其放在另一个List
中。但我只把它们作为整数。我怎么知道哪一个被检查了,因为我需要该项目的名称?
List<Integer> mSelectedItems = new ArrayList<>();
@Override
public void renderGenreList(List<Genre> genreList) {
CharSequence[] genreChar = convertGenreList(genreList);
genreDialog(genreChar);
}
private CharSequence[] convertGenreList(List<Genre> genreList) {
List<String> genreString = new ArrayList<>();
for (int i = 0; i < genreList.size(); i++) {
Genre genre = genreList.get(i);
genreString.add(genre.getName());
}
return genreString.toArray(new CharSequence[genreString.size()]);
}
private void genreDialog(CharSequence[] genres) {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder
.setTitle(R.string.multiple_choice_title)
.setMultiChoiceItems(genres, null, (dialog, which, isChecked) -> {
if (isChecked) {
mSelectedItems.add(which);
} else if (mSelectedItems.contains(which)) {
mSelectedItems.remove(Integer.valueOf(which));
}
})
.setPositiveButton(R.string.OK_button, (dialog, which) -> {
dialog.dismiss();
})
.setNegativeButton(R.string.CANCEL_button, (dialog, which) -> dialog.dismiss());
d = builder.create();
}
答案 0 :(得分:0)
您的mSelectedItems列表包含所选项目列表的位置。所以你可以在下面做所有项目
for (int i = 0; i < mSelectedItems.size(); i++) {
Genre genre = genreList.get(mSelectedItems.get(i));
// Here genre is one of the items selected and you can get all items in this loop
}
或第二方法是将值添加到mSelectedItems
而不是添加哪个获取值然后添加
替换 -
mSelectedItems.add(which);
带
mSelectedItems.add(genreList.get(which));
然后您将拥有mSelectedItems
所选项目列表。更新上面的删除方法。
第三种方式是拥有对话框的实例并从那里开始。
AlertDialog mAlert = builder.create();
// Display the alert dialog on interface
mAlert.show();
// get list of selected items
mAlert.getListView().getCheckedItemPositions();