Android RecyclerView滚动并将项目定位在顶部



我不确定RecyclerView是否很难做到这一点,我认为有一种简单的方法可以做到,但我遇到了一些困难。我有一个活动的RecyclerView,当我转到该活动时,我希望它滚动到一个项目。看起来很好。然而,我的问题是,假设一次只有5个项目可以放在屏幕上,而我们有6个项目,我们滚动到第5个或第4个项目,RecyclerView确实滚动了一点,但看起来不像是滚动到元素,因为它受到RecyclerView边界的限制。

如果我滚动到RecyclerView中的第4个或第5个项目,它会将其定位在视图的顶部,最后一个项目下方的区域将只是正常视图的背景色,我可以正常向上滚动吗?我希望我的解释是正确的。我不确定这是否可以轻松完成,而且我在XML设置或代码设置中犯了一个错误。

<merge xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<include
android:id="@+id/timelineSwitcherView"
layout="@layout/view_timeline_view_switcher"/>
<ViewAnimator
android:id="@+id/viewAnimator"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/timelineSwitcherView">
<RelativeLayout
android:id="@+id/timeLineRelativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/lighterBlue">
<android.support.v4.widget.SwipeRefreshLayout
android:id="@+id/timeLineSwipeRefreshLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="@+id/timeLineRecyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</android.support.v4.widget.SwipeRefreshLayout>
</RelativeLayout>

感谢在这方面提供的任何帮助和指导。

您应该使用

mRecyclerview.scrollTo(x,y);
mRecyclerview.scrollToPosition();

甚至更好:

mRecyclerview.smoothScrollBy( x , y);        
mRecyclerview.smoothScrollToPosition(List item position);

所以你需要得到Y的位置,或者列表中的子位置。

最新更新