RecyclerView внутри LinearLayout и NestedScrollView - Как прокрутить до верхней части элемента на определенной позиции? - PullRequest
1 голос
/ 31 января 2020

Я реализовал RecyclerView. Я хотел бы просмотреть прокрутить к началу элемента на 5-й позиции в RecyclerView. 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 голосов
/ 31 января 2020

scrollToPosition() необходимо использовать любым из следующих способов, чтобы восстановить позицию прокрутки в выбранной позиции. Вы можете сохранить выбранную позицию в onPause(), а затем восстановить впоследствии. Может быть два полезных способа: -

  1. Использование функции onSaveInstanceState() для сохранения состояния, как объяснено здесь .
  2. Использование общих преференций для сохранения позиции, и восстановление состояния после onCreateView.
...