一般列表刷新,会使用notifyDataChanged,会使列表整个刷新,虽然达到了效果,但是不美观。所以,如果可以做到只刷新需要刷新的item就好了。这里就有个特好用的方法,分享给大家。
/**
* 更新某一个item数据
* @param nearbyNewAnchorInfo
*/
public void updateNearbyAndNewAnchorData(RecyclerView recyclerView, NearByNewAnchorInfo nearbyNewAnchorInfo){
int headerCount = ((HeaderAndFooterWrapper) (recyclerView.getAdapter())).getHeadersCount();
//极致的item刷新优化
RecyclerView.ViewHolder viewHolder = recyclerView.findViewHolderForAdapterPosition(nearbyNewAnchorInfo.Index+headerCount);
if (viewHolder != null && viewHolder instanceof NearbyNewViewHolder) {
NearbyNewViewHolder itemHolder = (NearbyNewViewHolder) viewHolder;
itemHolder.nearbyView.updateData(nearbyNewAnchorInfo.StarLiveRooms,true);
itemHolder.newView.updateData(nearbyNewAnchorInfo.NearLiveRooms,true);
}
}
主要使用到的方法: public ViewHolder findViewHolderForAdapterPosition(int position)
/**
* Return the ViewHolder for the item in the given position of the data set. Unlike
* {@link #findViewHolderForLayoutPosition(int)} this method takes into account any pending
* adapter changes that may not be reflected to the layout yet. On the other hand, if
* {@link Adapter#notifyDataSetChanged()} has been called but the new layout has not been
* calculated yet, this method will returnnull
since the new positions of views
* are unknown until the layout is calculated.
*
* This method checks only the children of RecyclerView. If the item at the given
*position
is not laid out, it will not create a new one.
*
* When the ItemAnimator is running a change animation, there might be 2 ViewHolders
* representing the same Item. In this case, the updated ViewHolder will be returned.
*
* @param position The position of the item in the data set of the adapter
* @return The ViewHolder atposition
or null if there is no such item
*/
需要注意的是,这里的position指的是item在列表中的位置,而不是item数据在列表数据的位置。所以需要将列表中的头部视图计算进去,才可以获取到真正该位置上的item。