How to update/refresh specific item in RecyclerView

Elgendy picture Elgendy · Sep 8, 2015 · Viewed 190.1k times · Source

I'm trying to refresh specific item in RecyclerView.

Story: Whenever user clicks on item, it shows AlertDialog. User can type some text by clicking ok button. I want to show this text in this item and show invisible ImageView - declared in XML and adapter ViewHolder -

I used this function in AlertDialog Positive Button to update the item:

private void updateListItem(int position) {
  View view = layoutManager.findViewByPosition(position);
  ImageView medicineSelected = (ImageView) view.findViewById(R.id.medicine_selected);
  medicineSelected.setVisibility(View.VISIBLE);
  TextView orderQuantity = (TextView) view.findViewById(R.id.order_quantity);
  orderQuantity.setVisibility(View.VISIBLE);
  orderQuantity.setText(quantity + " packet added!");

  medicinesArrayAdapter.notifyItemChanged(position);
}

But this code not only changes the itemView at passed position, but also changes some of other itemView(s) as well!

How should I change specific itemView correctly by clicking on it?

Answer

Edson Menegatti picture Edson Menegatti · Sep 8, 2015

You can use the notifyItemChanged(int position) method from the RecyclerView.Adapter class. From the documentation:

Notify any registered observers that the item at position has changed. Equivalent to calling notifyItemChanged(position, null);.

This is an item change event, not a structural change event. It indicates that any reflection of the data at position is out of date and should be updated. The item at position retains the same identity.

As you already have the position, it should work for you.