1

当我从详细信息活动返回时,要从最后选择的 RecyclerView 项目中删除突出显示的背景颜色,我尝试了以下操作onResume()

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

这在onBindViewHolder()

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

onBindViewHolder()总是在之后调用,onResume()所以selectedPos == position给出了正确的结果,但我不明白为什么不早点调用它。

为什么我不必保存selectedPos在临时变量中并notifyItemChanged(temp)在更改后调用selectedPos

提前致谢。

4

1 回答 1

0

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()
}
于 2019-11-28T01:57:31.957 回答