简体   繁体   中英

onBindViewHolder not triggering for items in recycler view

I have a recycler view with 10 items. I scroll to the bottom of the page, and now I'm trying to call notifyItemChanged(pos) for the first item which is not visible since I scrolled down. When I call this, it is not triggering onBindViewholder() for the first item. So in short my question is when I call notifyItemChanged(pos) with a position that is not displaying on the screen, is it not triggering the onBindViewHolder() ?. This is my adapter code

@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;
    }

Your error is on your onItemCount method. NotifydatasetChanged calls onBindViewHolder for each of the items in your usertasks and goes as far as your usertasks.size. Change your onGetItemCount to this:

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

Now your notifyDatasetChanged will call onBindViewHolder as long as your usertasks is not null. If it is still not calling, then look for your usertasks as it is probably null

First create a method in recycler view adapter class, like to update:

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

    }

In your fragment class:

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

I was able to fix that. The issue is bind view holder is never triggered for the items that were already recycled. Since my logic was written in bind view holder it didn't work, instead I updated my list in the fragment and called notifyDataSetChanged.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM