Recyclerview - smoothScrollToPosition 到列表顶部,然后动画添加项目

Recyclerview - smoothScrollToPosition to Top of list and then animate the addition of item

我正在尝试创建一个 Recyclerview,它将首先滚动到顶部,然后以动画方式将项目添加到 recyclerview。

这是我目前的代码:

        while (!mLayoutManager.isSmoothScrolling()) {
            mRecyclerView.smoothScrollToPosition(0);
        }
        PostList.add(0, post);
        mAdapter.notifyItemInserted(0);
        mAdapter.notifyItemRangeChanged(1, PostList.size());

这会滚动到顶部,但是添加项目时不是动画的(尽管它已添加到列表中)。

我想是因为加法动画和smoothScrollToPosition动画是同时发生的,所以当它到达顶部时,加法动画已经结束了,所以我们看不到。

我可以使用 Handler.postDelayed 让我的滚动动画有一些时间来完成,但这不是可取的,因为我不知道 smoothScrollToPosition 动画完成的时间。

我猜你希望当 do while 完成时,滚动将完成。它不是这样工作的,滚动发生在动画帧中,如果你放置一个 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);

没有测试代码,但基本思想是添加滚动侦听器以在平滑滚动停止时收到通知,然后添加项目。