Update an item view in RecyclerView

时间:2017-04-24 17:30:54

标签: android android-recyclerview recycler-adapter

I have a RecyclerView which is getting list of favourite and Unfavourite item. There is a Star icon in the item onClick of which i am calling an API which return added to favorite or removed from favourite. Now i am Trying to update star icon in the RecyclerView

OnSuccess of my task i am updating my list with this code

adapterParcel.notifyItemChanged(position, modelParcelsArrayList);
                        adapterParcel.notifyDataSetChanged();

In my Adapter onBindViewHolder i am trying to update view by this code

if (singleModelParcels.is_favouriteParcel()) {
                itemListHolder.rpl_iv_favorite.setBackgroundResource(R.drawable.ic_action_fav_yellow);
            } else {
                itemListHolder.rpl_iv_favorite.setBackgroundResource(R.drawable.ic_action_fav_white);
            }

I am unable to figure out what should i do to update View of that item.

2 个答案:

答案 0 :(得分:2)

notifyDataSetChanged方法刷新recyclerView适配器中的项目,即。他们再次经历onBindViewHolder州。

如果您已正确修改对象以保持fav值(true / false) 然后在onBindViewHolder内你可以简单地访问该值,设置视图,如下所示:

 @Override
    public void onBindViewHolder(final ViewHolder holder, final int position) {
   Object object = objectList.get(position);
   if (object.isFav()){
     holder.favIcon.highlight();
   }else{
     holder.favIcon.unhighlight();
   }
}

所以你要做的就是调用适配器上的notifyDataSetChanged方法,onBindViewHolder方法中的代码会为你处理它!

检查我创建的类似项目here

答案 1 :(得分:0)

您也可以使用notifyItemChanged实现相同目的,但在这种情况下,您需要更新该位置的实体,这将刷新适配器中的视图。