【问题标题】:onBindViewHolder not triggering for items in recycler viewonBindViewHolder 未触发回收站视图中的项目
【发布时间】:2020-08-18 19:38:58
【问题描述】:

我有一个包含 10 个项目的回收站视图。我滚动到页面底部,现在我尝试调用notifyItemChanged(pos) 来获取自向下滚动以来不可见的第一个项目。当我调用它时,它不会为第一项触发onBindViewholder()。所以简而言之,我的问题是当我调用notifyItemChanged(pos) 的位置未显示在屏幕上时,它不会触发onBindViewHolder() 吗? 这是我的适配器代码

@SuppressLint("NewApi")
    @Override
    public void onBindViewHolder(@NonNull final UserTasksViewHolder holder, final int position) {
        if (usertasks != null) {
            final UserSessionTasksEntity current = usertasks.get(position);
            viewPos = prefs.getString(view_position, "");
            holder.taskCode.setText(current.getTaskCode());
            holder.taskName.setText(current.getTaskName());
    }

    @Override
    public int getItemCount() {
        if (usertasks != null)
            return usertasks.size();
        return 0;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public int getItemViewType(int position) {
        return position;
    }

【问题讨论】:

  • 你是通过适配器类更新位置
  • 我从片段类调用 notifyItemChanged()。
  • 从回收站视图适配器执行它,它会工作
  • 这可能是因为您没有正确设置 onItemCount 函数。 OnBindViewHolder 在列表大小的每个项目中调用一次。发布您的适配器代码
  • @MateoHervas 请看一下我的适配器代码

标签: android android-recyclerview


【解决方案1】:

您的错误在于您的 onItemCount 方法。 NotifydatasetChanged 为您的 usertasks 中的每个项目调用 onBindViewHolder,并一直到您的 usertasks.size。将您的 onGetItemCount 更改为:

@Override
public int getItemCount() {
    if (usertasks != null)
        return usertasks.size();
    else{
       return 0;
    }
     
}

现在,只要您的 usertasks 不为空,您的 notifyDatasetChanged 就会调用 onBindViewHolder。如果它仍然没有调用,则查找您的 usertasks,因为它可能为 null

【讨论】:

    【解决方案2】:

    首先在recycler view adapter类中创建一个方法,喜欢更新:

    public void setData(ArrayList<GridItem> newitems,int pos){ // this is new array
            this.mydata=newitems;//here you update your orignal data
            this.notifyItemChanged(pos);//here notify the change at particular position
    
        }
    

    在您的片段类中:

    //get your recyclerview  adapter and call the above method
    adapter.setData(newdata,position);
    

    【讨论】:

      【解决方案3】:

      我能够解决这个问题。问题是永远不会为已经回收的项目触发绑定视图持有者。由于我的逻辑是在绑定视图持有者中编写的,因此它不起作用,而是我在片段中更新了我的列表并调用了 notifyDataSetChanged。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-06-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多