android - Recyclerview 滚动到 NestedScrollView 内的特定位置
问题描述
假设,我在 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);
解决方案
这应该适用于我的情况
testRecyclerview.post(() -> {
float y = testRecyclerview.getY() + testRecyclerview.getChildAt(50).getY();
nestedScrollView.smoothScrollTo(0, (int) y);
});