Recycleview 滚动到 Nestedscrollview 中不起作用的位置

Dar*_*ana 7 android

我在嵌套滚动视图中实现了一个回收视图。但是回收视图滚动到位置方法不起作用。

下面是我的示例代码

  <?xml version="1.0" encoding="utf-8"?>
  <android.support.v4.widget.NestedScrollView 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

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


  <android.support.v7.widget.RecyclerView
      android:id="@+id/list_view"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

 </LinearLayout>

</android.support.v4.widget.NestedScrollView>
Run Code Online (Sandbox Code Playgroud)

下面是滚动的方法

RecyclerView.SmoothScroller smoothScroller = new LinearSmoothScroller(this) {
                @Override
                protected int getVerticalSnapPreference() {
                    return LinearSmoothScroller.SNAP_TO_START;
                }
            };
            smoothScroller.setTargetPosition(pos);
            recyclerView.getLayoutManager().startSmoothScroll(smoothScroller);
Run Code Online (Sandbox Code Playgroud)

Dar*_*ana 9

这就是我解决这个问题的方法

首先使用以下方法获取需要滚动的回收视图位置

final float y = recyclerView.getChildAt(selectedItem.getPos()).getY();
Run Code Online (Sandbox Code Playgroud)

然后将嵌套滚动视图滚动到该位置
nestedScrollingView.post(new Runnable() { @Override public void run() { nestedScrollingView.fling(0); nestedScrollingView.smoothScrollTo(0, (int) y); } });

不要忘记添加android:fillViewport="true"nestedscrollview

  • 谢谢你,它对我来说还有一个额外的步骤: `final float y = recyclerView.getY() + recyclerView.getChildAt(adapterPosition).getY(); scrollView.post(() -&gt; {scrollView.fling(0);scrollView.smoothScrollTo(0, (int) y); });` (2认同)

小智 6

问题是您需要滚动 NestedScrollView,而不是 RecyclerView。例如:

    final float y = recyclerView.getChildAt(selectedItem.getPos()).getY(); 

    scrollView.smoothScrollTo(0, y)
Run Code Online (Sandbox Code Playgroud)