Sim*_*mon 3 android adapter smooth-scrolling android-recyclerview
我正在尝试创建一个Recyclerview,它将首先滚动到顶部,然后将一个项目添加到recyclerview上.
这是我到目前为止的代码:
while (!mLayoutManager.isSmoothScrolling()) {
mRecyclerView.smoothScrollToPosition(0);
}
PostList.add(0, post);
mAdapter.notifyItemInserted(0);
mAdapter.notifyItemRangeChanged(1, PostList.size());
Run Code Online (Sandbox Code Playgroud)
这确实滚动到顶部,但项目的添加没有动画(虽然它被添加到列表中).
我认为这是因为加法动画与动画同时发生,smoothScrollToPosition因此当它到达顶部时,加法动画已经完成,所以我们看不到它.
我可以使用a Handler.postDelayed来给我的滚动动画一些时间来完成,但这并不可取,因为我不知道smoothScrollToPosition动画完成的时间.
我想你希望在完成的时候滚动完成.这不是它的工作方式,滚动发生在动画帧中,如果你要放一个while循环等待它完成,你的应用程序将冻结,因为你将阻止主线程.
相反,你可以做这样的事情:
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
public void onScrollStateChanged(RecyclerView rv, int state) {
if (state == RecyclerView.SCROLL_STATE_IDLE) {
PostList.add(0, post);
mAdapter.notifyItemInserted(0);
rv.removeOnScrollListener(this);
}
}
});
recyclerView.smoothScrollToPosition(0);
Run Code Online (Sandbox Code Playgroud)
没有测试代码,但基本的想法是添加一个滚动监听器,以便在平滑滚动停止时收到通知,然后添加项目.