android - 在 RecyclerView android 中禁用项目

标签 android android-recyclerview

我的 RecyclerView 是一个带有复选框的列表,页面底部是一个提交按钮。当我点击按钮时,复选框应该被禁用,但那些已经被选中的框的状态应该保留。此外,如何访问位于 RecyclerView.ViewHolder 中的复选框?请帮忙。

最佳答案

最好将此作为您正在建模的项目的属性。

因此,如果模型项目将具有您可以更改的“已启用”状态。

public class Model {

   private boolean isEnabled;
   private boolean isChecked;

   public void setEnabled(boolean enabled) { 
      isEnabled = enabled;
   }

   public void setChecked(boolean checked) {
      isChecked = checked;
   }

   public boolean isEnabled() {
      return isEnabled;
   }

   public boolean isChecked() {
      return isChecked;
   }
}

然后您的 ViewHolder 将在您每次绑定(bind)到它时检查此属性。此外,ViewHolder 本身将监听对其处理的 View 上的复选框的更改。

public class ModelViewHolder extends RecyclerView.ViewHolder implements CompoundButton.OnCheckChangeListener {
   private CheckBox checkBox;
   private Model boundItem;

   public ModelViewHolder(View itemView) {
       checkBox = (CheckBox) itemView.findItemById(R.id.checkBoxId);
       checkBox.setOnCheckChangeListener(this);
   }

   public void bind(Model model) {
       boundItem = model;
       getItemView().setEnabled(model.isEnabled());
       checkBox.setChecked(model.isChecked());
   }

   @Override
   public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
       boundItem.setChecked(isChecked);
   }
}

现在,这允许项目的状态在用户滚动时保持一致(因为 RecyclerItem 中的 View 被重新使用)。它还允许您在启用/禁用模型项目时更轻松地对项目使用 notifyItemChanged(int position)

关于android - 在 RecyclerView android 中禁用项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35776002/

相关文章:

android - 如何在 ArrayAdapter 中调用 getSupportFragmentManager()

android - 回收站 View 未调用 getItemCount

java - 如何使回收器 View 水平且类似于表格布局?

android - 未连接。调用 Connect 或等待 onConnected() 被调用

android - Firebase 获取子列表的子项

java - 使用 Context 对象从 fragment 内的 RecyclerView 访问 Activity 的 HashMap

Android Recyclerview 多个onclick项目

java - 项目单击监听器不适用于自动滚动回收器 View

java - 使用正则表达式验证可变长度字符串

android - 按下后退按钮时应用程序崩溃