【发布时间】:2016-10-25 13:57:40
【问题描述】:
我为RecyclerView 创建了一个custom layout manager。我已经通过 setAutoMeasureEnabled(true) 在我的经理的构造函数中启用了自动测量
当RecyclerView 的layout_height 设置为wrap_content 并使用此属性LayoutManager 能够根据其中的项目测量RecyclerView 的高度。它工作得很好,但是当我删除底部的最后一个项目时,正在播放删除动画,它会导致RecyclerView 在动画完成之前测量它的高度到结果高度。
看看这个 gif。 其中绿色背景是 RecyclerView
正如您可能猜到的那样,这种行为对于添加项目是正确的,因为在这种情况下,应该在动画之前测量容器
我该如何处理这种情况以在动画完成后处理RecyclerView 自动测量?
我在onLayoutChildren 中有所有子定位逻辑,但我认为发布它不需要这个问题,并且可能如此广泛和不清楚。
可能我应该手动处理 layoutManager 的 onMeasure 拦截器(当项目被删除时它调用了 4 次(在 onItemsRemoved 调用之前一次))。所以我可以在那里设置测量高度,基于高度,我在删除开始时收到:
@Override
public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state, int widthSpec, int heightSpec) {
super.onMeasure(recycler, state, widthSpec, heightSpec);
requestSimpleAnimationsInNextLayout();
if (!isAutoMeasureEnabled()) {
setMeasuredDimension(getWidth(), preHeight);
}
}
@Override
public void onItemsRemoved(RecyclerView recyclerView, int positionStart, int itemCount) {
super.onItemsRemoved(recyclerView, positionStart, itemCount);
setAutoMeasureEnabled(false);
new Handler(Looper.myLooper()).postDelayed(new Runnable() {
@Override
public void run() {
setAutoMeasureEnabled(true);
requestSimpleAnimationsInNextLayout();
requestLayout();
}
}, 400);
preHeight = //calculate height before deletion
}
如您所见,我提供了一个具有近似延迟 400ms 值的处理程序,它在动画完成后执行自动测量,因此这可能会导致所需的结果,但动画的持续时间不是静态的,我不会看到任何可能收听动画完成事件的可能性。
所以,期望的行为:
顺便说一下,LinearLayoutManager 的自动测量工作方式相同
如果你只用算法的文字描述给我指出正确的方向就足够了。
【问题讨论】:
-
我无法提高我的问题的质量,因为你在没有任何评论的情况下对我投了反对票
-
在我看来,这个问题被完美地提出并得到了完美的回答......
标签: android android-layout animation android-recyclerview