RecyclerView.Adapter.notifyItemMoved(0,1) scrolls screen

后端 未结 4 1614
旧巷少年郎
旧巷少年郎 2021-01-02 03:00

I have a RecyclerView managed by a LinearlayoutManager, if I swap item 1 with 0 and then call mAdapter.notifyItemMoved(0,1), the moving animation causes the screen to scroll

4条回答
  •  别那么骄傲
    2021-01-02 03:33

    Sadly the workaround presented by yigit scrolls the RecyclerView to the top. This is the best workaround I found till now:

    // figure out the position of the first visible item
    int firstPos = manager.findFirstCompletelyVisibleItemPosition();
    int offsetTop = 0;
    if(firstPos >= 0) {
        View firstView = manager.findViewByPosition(firstPos);
        offsetTop = manager.getDecoratedTop(firstView) - manager.getTopDecorationHeight(firstView);
    }
    
    // apply changes
    adapter.notify...
    
    // reapply the saved position
    if(firstPos >= 0) {
        manager.scrollToPositionWithOffset(firstPos, offsetTop);
    }
    

提交回复
热议问题