【问题标题】:RecyclerView inside LinearLayout and NestedScrollView - How to scroll to top of item on a certain position?LinearLayout 和 NestedScrollView 内的 RecyclerView - 如何滚动到某个位置的项目顶部?
【发布时间】:2020-05-17 05:30:17
【问题描述】:

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

【问题讨论】:

  • 您可以通过保存点击位置来处理它,在 onResume() 中您可以执行 scrollToPosition。添加您的编码部分以供单击,以便任何人都可以查看它。

标签: java android android-recyclerview android-nestedscrollview


【解决方案1】:

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

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

【讨论】:

  • 感谢您的回复。这是我的第一个问题,我错误地解释了我的问题。 scrollToPosition()不工作。我将 5 永久设置为检查它是否滚动到 RecyclerView 中的位置 5。没用
  • 'scrollToPosition(int position)' 参数指定到适配器的位置。在您共享的代码中,尝试在调用 'scrollToPosition(int p)' 之前设置适配器。
  • 我已经为scrollToPosition() 设置了适配器,但没有帮助:(你还有其他想法是什么问题吗?
猜你喜欢
  • 2018-07-13
  • 2019-07-08
  • 2018-10-26
  • 1970-01-01
  • 1970-01-01
  • 2019-05-05
  • 2021-12-10
  • 2017-06-13
  • 1970-01-01
相关资源
最近更新 更多