Android RecyclerView滚动到程序方式不起作用

7

我试图通过编程方式滚动到我的RecyclerView中的某个位置,目前为止我尝试过以下方法但都没有成功:

        musicList.getLayoutManager().smoothScrollToPosition(musicList, null, position);

        musicList.scrollToPosition(position);

        mLayoutManager.scrollToPosition(position);

        musicList.getLayoutManager().scrollToPosition(position);

有什么我忘了吗?

我定义了一个 LinearLayoutManager mLayoutManager; 并将其设置为 RecyclerView,如下所示:

    mLayoutManager = new LinearLayoutManager(this);
    musicList.setLayoutManager(mLayoutManager);

RecyclerView XML:

<android.support.v7.widget.RecyclerView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/musicList"
                android:scrollbars="vertical"
                android:scrollbarThumbVertical="@drawable/custom_scrollbar_vertical"/>
2个回答

15

你尝试过使用LinearLayoutManager的scrollToPositionWithOffset方法吗?

//position 2 and second param is offset 20
mLayoutManager.scrollToPositionWithOffset(2, 20);

这对我有效。希望对你也有效!


3
这对我起作用了,但我不明白为什么需要一个偏移量来完成这个操作... - Marian Pavel
5
什么是偏移量的必要性?为什么给定20? - Sachin Varma
非常感谢,这救了我的一天。我不知道 Google 的开发团队出了什么问题。滚动是一个动作,应该只需要一个方法来执行它,而不是 7 个(4 个在布局管理器上,3 个在 RecyclerView 上)。 - ozapa

1
附加说明:

折叠式 工具栏 展开 的情况下,建议的滚动功能不会正常工作。

似乎回收视图有一个固定的高度,而当工具栏展开时,回收器被向下移动,部分超出屏幕。因此,函数findLast[Completely]VisibleItemPosition()的结果也太高了。例如:最后可见的项目被告知是#9,但实际上只有项目#7真正在屏幕上。

我最终选择了这样的解决方法:
if (newPos > 2 /* or other number > 0 */)
{
    AppBarLayout l = findViewById(R.id.appbar);
    if (l != null)
    {
        l.setExpanded(false, true);  // collapse the bar, with animation
    }
}
mRecyclerView.scrollToPosition(newPos);

任何更好解决方案的提示都会受到赞赏!

这并没有提供问题的答案。您可以搜索类似的问题,或者参考页面右侧的相关和链接问题来找到答案。如果您有一个相关但不同的问题,请提出新问题,并包含此问题的链接以帮助提供上下文。请参阅:提问,获取答案,无干扰 - double-beep
您说得对,实际上这应该是对Kristiyan Varbanov答案的评论,即他的解决方案对我没有用,而且通常也不适用于折叠工具栏。不幸的是,stackoverflow不允许我写评论,因此我尝试写了一个答案。 - Andreas K. aus M.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接