all*_*mex 5 android position android-recyclerview
我希望带有LinearLayoutManager的RecyclerView在适配器更新后显示在特定项目上的滚动位置。(不是第一个/最后一个位置)是指第一个(重新)布局,此给定位置应位于可见区域。它不应以位置0在顶部进行布局,然后再滚动到目标位置。
我的适配器从itemCount = 0开始,将其数据加载到线程中,并在以后通知其实际计数。但是起始位置必须在count仍为0时已经设置好!
到目前为止,我使用了某种post Runnable包含方式,scrollToPosition但是它有副作用(从第一个pos开始,立即跳转到目标位置(0->目标),似乎不能与DiffUtil(0-> target-> 0)配合使用)
编辑:要澄清:我需要替代layoutManager.setStackFromEnd(true);,例如setStackFrom(position)。ScrollToPosition不起作用,如果我在itemCount仍为0时调用它,则它将被忽略。如果我在通知itemCount现在> 0时调用它,它将从0开始布局,并在跳转到目标位置后不久跳转。如果我使用DiffUtil.DiffResult.dispatchUpdatesTo(adapter)`,它将完全失败。(从0开始显示,然后滚动到目标位置,然后再次回到位置0)
小智 5
你可以试试这个,它会滚动到你想要的位置:
rv.getLayoutManager().scrollToPosition(positionInTheAdapter).
Run Code Online (Sandbox Code Playgroud)
我自己找到了解决方案:
我扩展了LayoutManager:
class MyLayoutManager extends LinearLayoutManager {
private int mPendingTargetPos = -1;
private int mPendingPosOffset = -1;
@Override
public void onLayoutChildren(Recycler recycler, State state) {
if (mPendingTargetPos != -1 && state.getItemCount() > 0) {
/*
Data is present now, we can set the real scroll position
*/
scrollToPositionWithOffset(mPendingTargetPos, mPendingPosOffset);
mPendingTargetPos = -1;
mPendingPosOffset = -1;
}
super.onLayoutChildren(recycler, state);
}
@Override
public void onRestoreInstanceState(Parcelable state) {
/*
May be needed depending on your implementation.
Ignore target start position if InstanceState is available (page existed before already, keep position that user scrolled to)
*/
mPendingTargetPos = -1;
mPendingPosOffset = -1;
super.onRestoreInstanceState(state);
}
/**
* Sets a start position that will be used <b>as soon as data is available</b>.
* May be used if your Adapter starts with itemCount=0 (async data loading) but you need to
* set the start position already at this time. As soon as itemCount > 0,
* it will set the scrollPosition, so that given itemPosition is visible.
* @param position
* @param offset
*/
public void setTargetStartPos(int position, int offset) {
mPendingTargetPos = position;
mPendingPosOffset = offset;
}
}
Run Code Online (Sandbox Code Playgroud)
它可以存储目标位置。如果onLayoutChildren由RecyclerView调用,则检查itemCount是否已经大于0。如果为true,则调用scrollToPositionWithOffset()。
因此,我可以立即告诉什么位置应该可见,但是在Adapter中的位置存在之前,不会告诉LayoutManager。
| 归档时间: |
|
| 查看次数: |
4629 次 |
| 最近记录: |