LinearLayout和NestedScrollView中的RecyclerView-如何在特定位置滚动到项目顶部?

时间:2020-01-31 14:20:24

标签: java android android-recyclerview android-nestedscrollview

我实现了RecyclerView。我想要一个视图滚动到RecyclerView中第5个位置的项目顶部。 scrollToPosition(5)不起作用

XML文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginTop="128dp"
    android:orientation="vertical">

    <androidx.core.widget.NestedScrollView
        android:id="@+id/nestedScrollView_mark"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <LinearLayout
            android:id="@+id/linearLayout_markView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <androidx.recyclerview.widget.RecyclerView
                android:id="@+id/recyclerView_marks"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="1dp" />

            <LinearLayout
                android:id="@+id/linearLayout_behavior"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="10dp"
                android:background="@drawable/layout_bg"
                android:orientation="vertical"
                android:visibility="invisible">

在片段中:

recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.getLayoutManager().scrollToPosition(5);
recyclerView.setAdapter(adapter);

1 个答案:

答案 0 :(得分:0)

scrollToPosition()需要通过以下任何一种方式使用,以将滚动位置恢复到所选位置。您可以将所选位置保存在onPause()中,然后进行恢复。 可能有两种有用的方法:-

  1. 使用onSaveInstanceState()功能保存状态,如here所述。
  2. 使用共享首选项存储位置,并在onCreateView之后恢复状态。