滚动位置/平滑滚动位置,用于嵌套滚动视图布局下的回收视图



我在嵌套的rcollview下有一个recyclerview。我想实现滚动到回收视图的特定位置,但我遇到了困难。xml代码是:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".HomeFragment"
android:background="#ffffff"
android:fillViewport="true"
android:id="@+id/nestedscrollview"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="1dp"
android:orientation="vertical"
>
<<some other layouts>>
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/home_blog_list"
android:layout_marginBottom="52dp"
/>


</LinearLayout>


</android.support.v4.widget.NestedScrollView>

我想实现home_blog_list循环视图到某个位置(比如26(的滚动位置。怎么做?P.S.-我已经将home_blog_list的嵌套滚动设置为false。请注意,我想将嵌套滚动视图滚动到recyclerview的特定行。我不希望出现只滚动回收视图的情况。提前感谢!

我偶然发现了同样的问题,我找到了一个简单的解决方案,不需要使用asif-ali建议的库进行重构。

在我当前的项目中,我有一个包含ConstraintLayoutNestedScrollView。这个ConstraintLayout包含一个由多个视图组成的复杂标头,然后是我的RecyclerView

和你一样,我需要整件事都可以滚动

也就是说,当用户希望看到特定RecyclerView中的项目时,您通常会调用:

RecyclerView#smoothScrollToPosition(int position(

但由于RecyclerView的高度设置为wrap_content,因此会显示完整列表,其中包含与其adapter中的项目一样多的ViewHolder。诚然,我们没有从回收中受益,但为什么我们需要ScrollView?使用@asif-ali解决方案肯定会带来回收优化,但这不是重点。

因此,我们有一个完全布局的RecyclerView。为了滚动到特定项目(ViewHolder#itemView(位置,您可以执行以下操作:

final void smoothScrollToPosition(final int position) {
final ViewHolder itemViewHolder = this.recyclerView.findViewHolderForAdapterPosition(position);
// at this point, the ViewHolder should NOT be null ! Or else, position is incorrect !
final int scrollYTo = (int) itemViewHolder.itemView.getY();
// FYI: in case of a horizontal scrollview, you may use getX();
this.nestedScrollView.smoothScrollTo(
0, // x - for horizontal
scrollYTo
);
}

就是这样!在这样做之后(在我的测试用例中(,child可能不完全可见,所以我建议将itemView的一半高度添加到scrollYTo变量中,以确保nestedScrollView足够滚动。如果您这样做,您可能还想检查nestedScrollView必须滚动到哪个方向(向上,然后删除半高,或者向下,然后添加半高。


[编辑1]

经过进一步的测试和研究,基于这个答案:https://stackoverflow.com/a/6831790/3535408以CCD_ 16为目标实际上是更好和更简单的。在我的应用程序上,它完美地工作。

因此,更新后的代码如下所示:

final void smoothScrollToPosition(final int position) {
final ViewHolder itemViewHolder = this.recyclerView.findViewHolderForAdapterPosition(position);
// at this point, the ViewHolder should NOT be null ! Or else, position is incorrect !
// FYI: in case of a horizontal scrollview, you may use getX();
this.nestedScrollView.smoothScrollTo(
0, // x - for horizontal
itemViewHolder.itemView.getBottom()
);
}

我想这就是你想要的,看看:链接

最新更新