我正在传递一个整数数组列表,该列表保存选择并根据选择检索它,但是当我从检查选择中删除该项目时,它并不是从以文本显示的数组列表中删除。这是我处理多重检查的逻辑。
public class MainFragment extends Fragment {
private Button buttonUser;
String[] listItems;
boolean[] checkedItems;
ArrayList<Integer> mUserItems = new ArrayList<>();
private Context context;
private AppCompatTextView compatTextView;
public static MainFragment newInstance() {
return new MainFragment();
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
listItems = getResources().getStringArray(R.array.person_array);
checkedItems = new boolean[listItems.length];
context = getActivity();
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
buttonUser = (Button) view.findViewById(R.id.buttonUser);
compatTextView = (AppCompatTextView) view.findViewById(R.id.text_view_selection);
buttonUser.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setTitle("Select Person");
alert.setMultiChoiceItems(listItems, checkedItems, new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if (isChecked) {
if (!mUserItems.contains(which)) {
mUserItems.add(which);
}
} else if (!mUserItems.contains(which)){
mUserItems.remove(which);
}
}
});
alert.setCancelable(false);
alert.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String items = "";
for (int i = 0; i < mUserItems.size(); i++) {
items = items.concat(listItems[mUserItems.get(i)]);
if (i != mUserItems.size() - 1) {
items = items + ", ";
}
compatTextView.setText(items);
}
}
});
alert.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog dialog = alert.create();
dialog.show();
}
});
return view;
}
}
而且我没有掌握逻辑的这一部分如何处理
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if (isChecked) {
if (!mUserItems.contains(which)) {
mUserItems.add(which);
}
} else if (!mUserItems.contains(which)){
mUserItems.remove(which);
}
}
这是正确的,但是当我从警报对话框中取消选择时,列表不会更新并显示以前的检查数据。
答案 0 :(得分:0)
我认为,如果isChecked为false,则else if部分将产生false。可能是这样吗:: else if (mUserItems.contains(which))