NarenderNishad
NarenderNishad

Reputation: 1068

Update an item view in RecyclerView

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.

Upvotes: 0

Views: 2924

Answers (2)

Aditi
Aditi

Reputation: 389

You can also achieve the same by using notifyItemChanged but in that scenario you will need to update the entity at that position which would refresh the view in adapter.

Upvotes: 0

MadScientist
MadScientist

Reputation: 2164

The notifyDataSetChanged method refreshes the items in the recyclerView adapter i.e . they again go through the onBindViewHolder state.

if you have modified you object properly to hold the fav value (true/false) then inside the onBindViewHolder you can simple access that value an set the view, something like this:

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

So all you have to do is call the notifyDataSetChanged method on the adapter and the code inside the onBindViewHolder mthod will handle it for you!

Check a similar project created by me, here

Upvotes: 2

Related Questions