NestedScrollView 内的 Recyclerview - 滚动到底部

Recyclerview inside NestedScrollView - Scroll to bottom

我在 NestedScrollView 里面有一个 RecyclerView:

        <android.support.v4.widget.NestedScrollView
            android:layout_width="match_parent"
            android:layout_height="@dimen/_100sdp">
            <android.support.v7.widget.RecyclerView
                android:id="@+id/recycler_view_chat"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:minHeight="@dimen/_100sdp"

                android:layout_marginLeft="@dimen/_30sdp"
                android:layout_marginRight="@dimen/_30sdp"
                android:background="@color/bright_grey"

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

我的 RecyclerView 正在填充 onCreate()

中的项目

在设备上,您会在最顶部看到 RecyclerView 的第一项,必须向下滚动 NestedScrollView 才能看到最后一项。

因为我的项目是按发送时间排序的聊天消息,所以我需要 NestedScrollView 一直向下滚动,这样用户就可以首先看到最新的聊天消息,而不必首先滚动。

对此有什么想法吗?

鉴于您的 RecyclerView 是您 NestedScrollView 的独生子,您最好完全删除 NestedScrollView,而不是将固定高度应用于 RecyclerView.像这样:

<android.support.v7.widget.RecyclerView
    android:id="@+id/recycler_view_chat"
    android:layout_width="match_parent"
    android:layout_height="@dimen/_100sdp"
    android:layout_marginLeft="@dimen/_30sdp"
    android:layout_marginRight="@dimen/_30sdp"
    android:background="@color/bright_grey" />

这样做可以让 RecyclerView 本身管理滚动,而不是父滚动视图。 允许您利用 LinearLayoutManager 的 属性 来实现您想要的。

反向布局 -- 设置此项将 "invert" 您的列表;适配器中的第一项将出现在列表的底部,RecyclerView 的默认滚动位置将一直滚动到底部。

https://developer.android.com/reference/android/support/v7/widget/LinearLayoutManager.html#setReverseLayout(boolean)

LinearLayoutManager lm = new LinearLayoutManager(this);
lm.setReverseLayout(true);

如果您遇到同样的问题并希望保留 NestedScrollView。 它会像这样工作。

Handler(Looper.getMainLooper()).postDelayed({
                        binding.nestedScrollView.smoothScrollTo(
                            0,
                            binding.recyclerview.measuredHeight,
                            500
                        )
                        // binding.nestedScrollView.scrollTo(0, binding.recyclerview.measuredHeight)
                        // binding.nestedScrollView.smoothScrollTo(0, binding.recyclerview.measuredHeight)
                    }, 50L)

对我来说,它没有立即起作用。