首页 > 解决方案 > Recyclerview smoothScrollToPosition 在android中不起作用

问题描述

我在 NestedScrollView 中使用 Recycler 视图,我的代码在这里

<androidx.core.widget.NestedScrollView
        android:id="@+id/rvSV"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fillViewport="true"
        android:scrollbars="none"
        tools:ignore="UselessParent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">


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

        </LinearLayout>

    </androidx.core.widget.NestedScrollView>

使用适配器将值加载到回收器视图后,我需要滚动到特定位置。所以我正在使用

 recyclerView.smoothScrollToPosition(scroll_value);

它不工作。所以我使用以下代码滚动到位置。那也行不通。

     SectionRecyclerViewAdapter adapter = new SectionRecyclerViewAdapter(getActivity(), sectionModelArrayList, this, bottomNavigation);
    recyclerView.setAdapter(adapter);
   float y;
    if (scroll_value == 0 || scroll_value == 1) {
        y = recyclerView.getChildAt(0).getY();
    } else {
        y = recyclerView.getChildAt(scroll_value - 1).getY();
    }


    rvSV.postDelayed(new Runnable() {
        @Override
        public void run() {
            rvSV.fling(0);
            rvSV.smoothScrollTo(0, (int) y);
        }
    }, 200);
    adapter.notifyDataSetChanged();

谁能告诉我如何解决这个问题?提前致谢。

标签: androidandroid-recyclerviewsmooth-scrollingnestedrecyclerview

解决方案


尝试添加recyclerview依赖

dependencies
{
 implementation "androidx.recyclerview:recyclerview:1.2.1"
 implementation "androidx.recyclerview:recyclerview-selection:1.1.0"
}

推荐阅读