我想知道在多次重复使用回收器视图时保存已检查状态的最佳方法是什么?
我有一个包含15个选项的可扩展列表视图,这15个选项中的每一个都有5个子项。单击时,每个子项都转到具有3个片段选项卡的活动。每个选项卡都有自己的回收站视图。我已经设置了适配器,因此它通过添加整数来了解它所在的片段,并且在将适配器设置为recycleler视图时,它会将选中标记从选项卡保存到选项卡。 (因此,如果我在第一个标签中,检查3个项目,切换标签,检查2个项目,它将正确保存。)
这是我的Recycler视图适配器,我在其中添加整数:
public class MyRecyclerAdapter extends RecyclerView.Adapter<MyViewHolder> {
Context mContext;
ArrayList<Workout> workout;
SharedPreferences prefs;
int firstSecondOrThird;
int colorResId = R.color.defaultcard;
public MyRecyclerAdapter(Context context, ArrayList<Workout> workout, int thePosition) {
mContext = context;
this.workout = workout;
this.firstSecondOrThird = thePosition;
}
以下是我将适配器设置为回收器视图(第一个选项卡)的选项卡片段:
//RECYCLERVIEW
final RecyclerView rv = (RecyclerView) view.findViewById(R.id.mRecyclerMon);
rv.setLayoutManager(new LinearLayoutManager(this.getActivity()));
rv.setAdapter(new MyRecyclerAdapter(this.getActivity(), getMondayWorkout(), 1));
第二个标签:
// //RECYCLERVIEW
final RecyclerView rv = (RecyclerView) view.findViewById(R.id.mRecyclerWed);
rv.setLayoutManager(new LinearLayoutManager(this.getActivity()));
rv.setAdapter(new MyRecyclerAdapter(this.getActivity(), getWedWorkout(), 2));
不幸的是,当我回到exp列表视图并单击另一个子项时,这些检查标记仍然存在,因为它只保存选项卡而不是单击哪个子项。
以下是我保存复选标记的方法(在回收器适配器onBindViewHolder中):
@Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
holder.exercise.setText(workout.get(position).getExercise());
holder.percent.setText(workout.get(position).getPercent());
holder.reps.setText(workout.get(position).getReps());
holder.weight.setText(workout.get(position).getWeight());
holder.check1.setOnCheckedChangeListener(null);
prefs = mContext.getSharedPreferences("checkState", Context.MODE_PRIVATE);
holder.check1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
prefs.edit().putBoolean(firstSecondOrThird + "checkState" + position, isChecked).apply();
}
});
holder.check1.setChecked(prefs.getBoolean(firstSecondOrThird+"checkState"+position, false));
}
我想知道让回收者视图保存每个子项的复选框状态的最佳方法。 谢谢你的帮助。
答案 0 :(得分:2)
我不确定这会解决您的问题,但在我的情况下,它可以工作,但我相信它会给您一个想法
SparseBooleanArray selectedItems = new SparseBooleanArray();
mCheckBox.setVisibility(View.VISIBLE);
mCheckBox.setChecked(!mCheckBox.isChecked());
if (selectedItems.get(getAdapterPosition(), false)) {
selectedItems.delete(getAdapterPosition());
v.setSelected(false);
} else {
selectedItems.put(getAdapterPosition(), true);
v.setSelected(true);
}
答案 1 :(得分:0)
由于您的情况很复杂,我建议将适配器本身设置为点击的监听器,让它保存数据,并让它在onBind函数中设置值。另外,在onBind函数中,设置一个标签来标识每个CheckBox,这样适配器就可以通过getTag来知道点击了哪个值。