我有以下XML布局。我在Coordinator布局中使用了recycler。虽然当我手动滚动时,它按预期工作。但是当我调用
有什么办法可以将Recycler View中的项目拉到屏幕顶部吗?
mRecyclerView.getLayoutManager().scrollToPosition(selectedPosition);
或mRecyclerView.scrollToPosition(selectedPosition);
来以编程方式滚动recycler视图时,它不会滚动。下面是我的XML代码。 <android.support.design.widget.AppBarLayout
android:id="@+id/tab_appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/backgroundBlue">
<android.support.design.widget.CollapsingToolbarLayout
android:id="@+id/collapsing_toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_scrollFlags="scroll|enterAlways">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="@dimen/standard_layout_margin"
android:layout_marginRight="@dimen/standard_layout_margin"
app:cardElevation="@dimen/small_layout_margin"
app:cardUseCompatPadding="true">
<include
android:id="@+id/details"
layout="@layout/detail_layout" />
</android.support.v7.widget.CardView>
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="@dimen/standard_layout_margin"
android:layout_marginRight="@dimen/standard_layout_margin"
app:cardElevation="@dimen/small_layout_margin"
app:cardUseCompatPadding="true">
<include layout="@layout/store_layout" />
</android.support.v7.widget.CardView>
</LinearLayout>
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/collapsing_toolbar"
android:layout_marginLeft="@dimen/standard_layout_margin"
android:layout_marginRight="@dimen/standard_layout_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
在特定情况下,我希望我的 RecyclerView 中的特定项目出现在屏幕顶部。以下是我的 Java 代码:
if (selectedPosition != 0) {
AppBarLayout appBarLayout = (AppBarLayout) mView.findViewById(R.id.tab_appbar);
CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) appBarLayout.getLayoutParams();
AppBarLayout.Behavior behavior = (AppBarLayout.Behavior) params.getBehavior();
if(behavior!=null) {
behavior.onNestedPreScroll(mCoordinatorLayout, appBarLayout, mRecyclerView, 0, (int) mRecyclerView.getY(), new int[]{0, 0});
mRecyclerView.getLayoutManager().scrollToPosition(selectedPosition);
mRecyclerView.scrollToPosition(selectedPosition);
}
}
有什么办法可以将Recycler View中的项目拉到屏幕顶部吗?