Recyclerview 特别好用的局部刷新item方法
一般列表刷新,會使用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 return null 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 at position or null if there is no such item
*/
需要注意的是,這里的position指的是item在列表中的位置,而不是item數據在列表數據的位置。所以需要將列表中的頭部視圖計算進去,才可以獲取到真正該位置上的item。
總結
以上是生活随笔為你收集整理的Recyclerview 特别好用的局部刷新item方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android设置网络图片为手机背景图片
- 下一篇: 几天几夜,终解移动MM计费SDK接入bu