繁体   English   中英

LinearLayout 和 NestedScrollView 中的 RecyclerView - 如何滚动到某个位置的项目顶部?

[英]RecyclerView inside LinearLayout and NestedScrollView - How to scroll to top of item on a certain position?

我实现了 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);

scrollToPosition()需要与以下任意一种方式一起使用,才能将滚动位置恢复到选中的位置。可以在onPause()保存选中的位置,然后再恢复。 可能有两种有用的方法:-

  1. 使用onSaveInstanceState()函数保存状态说明这里
  2. 使用 Shared Prefereneces 存储位置,并在onCreateView之后恢复状态。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM