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。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值