在 NestedScrollView 内时,回收器视图加载大数据非常慢

问题描述 投票:0回答:5

我已将

RecyclerView
添加到我的
NestedScrollView
中。基本上我希望 RecyclerView 与其他视图一起滚动。我面临的问题是,对于一小部分数据,它工作正常,但对于大量数据(200 个条目),每当我启动活动时,它都会冻结大约 3-5 秒,然后加载。我删除了
NestedScrollView
,它工作完美,但它没有提供我想要的行为。

(作为额外信息,我正在从 SQLite 数据库加载数据。滚动没有问题,因为它很平滑。唯一的问题是活动冻结了一段时间)

<android.support.v4.widget.NestedScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent">

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

                <... Some other Views ...>

                <android.support.v7.widget.RecyclerView
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:orientation="vertical">

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

            </LinearLayout>

        </android.support.v4.widget.NestedScrollView>
java android android-recyclerview android-nestedscrollview
5个回答
18
投票

这盒

RecyclerView
里面有
NestedScrollView

RecyclerView
正在调用
onCreateViewHolder()
次,次数等于您的数据大小。

如果数据有 200 项,则会冻结

onCreateViewHolder()
被调用 200 次。


0
投票

上面所说的问题是因为 RecyclerView 作为 NestedScrollView 中的子项或子子项,当您使用 WRAP_CONTENT 或 MATCH_PARENT 作为 RecyclerView 的高度时,其高度测量为不定式。

为我解决这个问题的一个解决方案是将 RecyclerView 高度设置为固定大小。您可以将高度设置为 dp 值,或者如果您的要求需要垂直不定式 RecyclerView,则可以将其设置为与设备高度匹配的像素值。

这里是在 kotlin 中设置 recyclerView 大小的片段

    val params = recyclerView.layoutParams
    params.apply {
            width = context.resources.displayMetrics.widthPixels
            height = context.resources.displayMetrics.heightPixels
    }
    recyclerView.layoutParams = params

0
投票

我也遇到了同样的问题! 解决方案是将 NestedScrollView 更改为 SwipeRefreshLayout。

添加此选项以启用/禁用工具栏滚动:

ViewCompat.setNestedScrollingEnabled(recyclerView, true);


0
投票

是的,答案有点晚了,但我认为这会阻止你 冻结您的RecyclerView在任何类型的可滚动视图中,例如 另一个RecyclerViewScrollViewNestedScrollViewMotionView等...

您所要做的就是给您的RecyclerView一个固定的高度。

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

-5
投票

正如 Nancy 所说,recyclerview.setNestedScrollingEnabled(false);将解决滚动卡住的问题。我也遇到过这类问题,并通过 false NestedScroll 解决了。

© www.soinside.com 2019 - 2024. All rights reserved.