Why can I call notifyItemChanged() in onResume() before data has changed?

378 views Asked by At

To remove the highlighting background color from the last selected RecyclerView item when I return from my details activity, I tried this in onResume():

mAdapter.notifyItemChanged(mAdapter.selectedPos);
mAdapter.selectedPos = RecyclerView.NO_POSITION;

and this in onBindViewHolder():

viewHolder.itemView.setSelected(selectedPos == position);

onBindViewHolder() is always called after onResume() so selectedPos == position gives the correct result but I don't understand why it's not called earlier.

Why don't I have to save selectedPos in a temp variable and call notifyItemChanged(temp) after the change of selectedPos?

Thanks in advance.

1

There are 1 answers

0
Prabudda Fernando On

onResume in called after the when you go to other activity and come back, its part of lifecycle of Activity. But onBindViewHolder is method which is related to adapter design pattern,its called continuesly with you scrolling its the place where adapter generate the cell items. therefore what ever changes need to be apply on this method and you can use notifyItemChanged(position) to trigger that change.

there is other way to implement: this will be a proper implementation,to remove the highlighting background color from the last selected RecyclerView, you have to keep some attribute on your adapter Item list what is hilighted.

ListItemModel{
 // ohter attributes goes here
 Boolean isSelected = false; // encapsulate
}

in the adapter lists items as follows,

private List<ListItemModel> itemList = new ArrayList()
viewHolder.itemView.setSelected(itemList[position]);

in the adapter

public void unselectAll(){
 for(ListItemModel item: itemList){
  item.isSelected = false
 }
 notifyItemChanged()
}