我有切换视图的动态添加权限列表。在onBindViewHolder中我使用setOnCheckedChangeListener分别更新每个开关的已检查状态,但是当我离开适配器时,开关状态都被重置为未选中。
这是我的onCreateViewHolder和onBindViewHolder
@Override
public PermisssionViewHolder onCreateViewHolder(final ViewGroup parent, int viewType) {
//Inflate view
View view = LayoutInflater.from(RjioSettingsApplication.get()).inflate(R.layout.permission_info_layout, parent, false);
final PermisssionViewHolder holder = new PermisssionViewHolder(view);
holder.getRootView().setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (clickListener != null) {
clickListener.onItemClicked(holder.getAdapterPosition());
if (holder.getPermissisonSwitch().isChecked()) {
holder.getPermissisonSwitch().setChecked(false);
} else {
holder.getPermissisonSwitch().setChecked(true);
}
}
}
});
return holder;
}
@Override
public void onBindViewHolder(final PermisssionViewHolder holder, final int position) {
super.onBindViewHolder(holder, position);
final PermisssionItem permission = items.get(position);
//Permission switch view
holder.getPermissisonSwitch().setOnCheckedChangeListener(null);
holder.getPermissisonSwitch().setChecked(items.get(position).isPermissionChecked());
holder.getPermissisonSwitch().setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
items.get(position).setPermissionChecked(true);
} else {
items.get(position).setPermissionChecked(false);
}
System.out.println("################## IS CHECKED " + isChecked);
notifyDataSetChanged();
}
});
//Permission title
holder.getTitle().setText(permission.getPermission());
}
答案 0 :(得分:1)
在数据列表模型中创建变量 boolean 。
private boolean isChecked;
public boolean isChecked() {
return isChecked;
}
public void setChecked(boolean checked) {
isChecked = checked;
}
然后将 RecyclerView 中的项目检查为
VHitem.checkIndividual.setOnCheckedChangeListener((compoundButton, checked) -> {
if (!onBind) {
selectIndividualCheckBox(checked, holder.getAdapterPosition());
}
});
private void selectIndividualCheckBox(boolean isChecked, int position) {
Model model = model.get(position);
model.setChecked(isChecked);
notifyDataSetChanged();
}