首页 文章

使用setHasStableIds和notifyDatasetChanged运行RecyclerView的预测动画

提问于
浏览
2

我在适配器中使用setHasStableIds并因各种原因调用整个notifyDatasetChanged而不是notifyItemXYZ . 我从setHasStableIds(true)开始得到简单的动画,但是当删除项目时,屏幕外的项目应该在屏幕上滑动,只是淡入 . (正如在Chet Haase中关闭预测动画的情况一样#2471213_) . 当我使用notifyItemRemoved时,它工作(但我的其他代码变得非常不方便)

TLDR; is there a way to get predictive (not only simple) animations when using setHasStableIds & notifyDatasetChanged with RecyclerView? (other than using notifyItemRemoved)

1 回答

  • 0

    几年前被问到,但也许对于寻找这种方式的人来说这会有所帮助 .

    您可以在布局管理器中覆盖getExtraLayoutSpace方法,以返回(例如)至少平均项目大小(以像素为单位)(隐藏屏幕外的非预测动画) .

    rv.setLayoutManager(new LinearLayoutManager(rv.getContext()) {
            @Override
            protected int getExtraLayoutSpace(RecyclerView.State state) {
                return Math.max(averageItemSizePx, super.getExtraLayoutSpace(state));
            }
    });
    

    当然,它有性能成本,所以要小心 .

    但有时这种方法会为您提供不可预测的动画 - 它取决于最后的滚动方向(来自LinearLayoutManager来源)

相关问题