Dynamically adding Views in a RecyclerView only to

2019-01-27 13:43发布

I'm dynamically adding Views to my items in a RecyclerView. These added Views should only be related to the item which they're added to, but I'm having a problem when I scroll. It seems the View is recycled and a new item is loaded, but those previously added views are still there, only now on the wrong item.

I'm assuming that it's just because the ViewHolder is being reused, so the added items show up again with a new item, when loaded.

How would one go about solving this?

8条回答
啃猪蹄的小仙女
2楼-- · 2019-01-27 14:05

You should take any Empty Layout like Linearlayout in your child item layout XML and then add views into that LinearLayout of your particular item in this way when you scroll List all of you child views which you have added to LinearLayout also scroll with that item .

查看更多
该账号已被封号
3楼-- · 2019-01-27 14:13

Based on this:

but those previously added Views are still there, but now on the wrong item.

Basically, as per the RecyclerView documentation, You have to reset the views everytime inside the onBindViewHolder() method,

so let say, you have a method that sets a view param if its your profile, so the code for the same goes as follows,

if (list.get(position).getId()==PreferenceManager.getUserID())
{
  // do some view change here
setViewParam(true);
}else
{
  // reset the view change here
setViewParam(false);
}

So what you're doing here is giving recycled ViewHolder a chance to reset. Do comment if you need help!

查看更多
登录 后发表回答