【问题标题】:Recyclerview scroll to specific position inside NestedScrollViewRecyclerview 滚动到 NestedScrollView 内的特定位置
【发布时间】:2020-02-24 05:53:39
【问题描述】:

假设,我在 RecyclerView 中有 40 个项目,并且想要滚动到项目编号 20

这是我的 XML 的样子:-

<?xml version="1.0" encoding="utf-8"?>
<androidx.core.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/nestedScrollView"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <androidx.coordinatorlayout.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <View
                android:layout_width="match_parent"
                android:layout_height="1000dp"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintTop_toTopOf="parent"/>


            <androidx.recyclerview.widget.RecyclerView
                android:id="@+id/testRecyclerview"
                android:layout_width="match_parent"
                android:layout_height="match_parent"/>

        </androidx.constraintlayout.widget.ConstraintLayout>

    </androidx.coordinatorlayout.widget.CoordinatorLayout>

</androidx.core.widget.NestedScrollView>

Java 代码,我使用 onCreate() 在 RecyclerView 中设置适配器:

            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
            testRecyclerview.setLayoutManager(linearLayoutManager);
            adapter = new ProductsAdapter(getActivity(), productModels);
            testRecyclerview.setAdapter(adapter);

在LinearLayout的情况下,效果很好,但是当我们使用NestedScrollView时就不行了

testRecyclerview.getLayoutManager().scrollToPosition(20);

【问题讨论】:

    标签: android android-recyclerview android-nestedscrollview


    【解决方案1】:

    这应该适用于我的情况

     testRecyclerview.post(() -> {
                float y = testRecyclerview.getY() + testRecyclerview.getChildAt(50).getY();
                nestedScrollView.smoothScrollTo(0, (int) y);
            });
    

    【讨论】:

    • 在 recycleview xml 中试试这个 android:nestedScrollingEnabled="false"
    • 100以上是什么(我的意思是什么是offset)
    • 从顶部到recycleview item的间距
    • 在 recyclerview 中尝试使用 false 为 nestedScrollingEnabled,但没有成功
    • 你能分享你的java文件吗?我会检查我是否有一些问题,因为在我的情况下这会起作用
    猜你喜欢
    • 2018-10-26
    • 1970-01-01
    • 1970-01-01
    • 2020-06-01
    • 2017-04-08
    • 1970-01-01
    • 2017-12-17
    • 1970-01-01
    • 2019-05-25
    相关资源
    最近更新 更多