模仿微信消息列表(RecycleView)双击移动未读消息

83 阅读1分钟

模仿微信消息列表(RecycleView)双击移动未读消息

相信你们在工作中会遇到这样的需求,在会话列表需要支持双击移动未读消息, 下面给出这种情况的代码写法

bb71184a117f707a27b0cb24c6facf50 00_00_00-00_00_30.gif

private int lastUnreadIndex = -1;
private List<Integer> unreadIndexs = new ArrayList<>();
 // 单个item高度
private int itemHeight = DisplayUtils.dp2px(100f);

   
public void scrollToUnreadMessage() {
        LayoutManager mLayoutManager = getLayoutManager();
        if (mLayoutManager == null) return;
        if (!(mLayoutManager instanceof LinearLayoutManager)) return;

        LinearLayoutManager mLinearLayoutManager = (LinearLayoutManager) mLayoutManager;
        unreadIndexs.clear();

        for (int i = 0;i< mAdapter.getItemCount(); i++) {
            ConversationInfo mConversationInfo = mAdapter.getItem(i);
            if (mConversationInfo.getUnRead() > 0) {
                unreadIndexs.add(i);
            }
        }

        int unreadPos = 0;
        if (unreadIndexs.size() > 0) {
            lastUnreadIndex = (++lastUnreadIndex) % unreadIndexs.size();
            unreadPos = unreadIndexs.get(lastUnreadIndex);
        }
        // 所有的移动距离都以 firstVisibleItemPosition 来做参照
        int firstVisibleItemPosition = mLinearLayoutManager.findFirstVisibleItemPosition();
        // 获取到当前参照view的偏移量
        View firstView = mLinearLayoutManager.findViewByPosition(firstVisibleItemPosition);
        if (firstView == null) return;
        if (firstView.getHeight() != 0) {
            itemHeight = firstView.getHeight();
        }
        int top = firstView.getTop();
        // 移动目标位置大于参照view postion
        // (这里item为等高)如果包含headview移动距离必须考虑到Headview的高度
        if (unreadPos > firstVisibleItemPosition) {
            int transPostion = unreadPos - firstVisibleItemPosition;
            smoothScrollBy(0, (transPostion * itemHeight + top));
            // 移动目标位置小于参照view postion
        } else if (unreadPos < firstVisibleItemPosition) {
            int transPostion = firstVisibleItemPosition - unreadPos;
            smoothScrollBy(0, -(transPostion * itemHeight - top));
        } else {
            // 移动目标位置等于参照view postion
            smoothScrollBy(0, top);
        }
    }
    ```
    
    [Demo 下载链接](https://sj.qq.com/appdetail/com.lujianfei.phoneinfo?&from_wxz=1)