gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 09:07:54 25 4
gpt4 key购买 nike

我实现了RecyclerView。我想要一个 View 滚动到 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">

在 fragment 中:

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

最佳答案

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

  1. 按照说明使用 onSaveInstanceState() 函数保存状态 here .
  2. 使用共享首选项存储位置,并在 onCreateView 之后恢复状态。

关于java - LinearLayout 和 NestedScrollView 中的 RecyclerView - 如何滚动到某个位置的项目顶部?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60005688/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com