gpt4 book ai didi

android - RecyclerView 在调用 notifyDataSetChanged() 时跳到顶部

转载 作者:行者123 更新时间:2023-12-02 04:21:34 26 4
gpt4 key购买 nike

我有一个包含 swipeRefreshLayout 的 fragment 和无限recyclerView在里面。我的 fragment 布局代码类似于:

<androidx.constraintlayout.widget.ConstraintLayout
.
.
.
android:layout_height="match_parent"
android:layout_width="match_parent"
android:clickable="true"
android:focusable="true"
android:focusableInTouchMode="true">


<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
.
.
.
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="parent" >

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

</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

我在 onViewCreated() 中设置了 recyclerView 的适配器并调用notifyDataSetChanged()onResume() .在 Samsung Galaxy A5 等某些设备中,当用户返回 fragment 和 notifyDataSetChanged 时叫,recyclerView移动到顶部并显示第一项。

我该如何防止这种情况发生?提前致谢。

更新:这是我的onResume()调用 notifyDataSetChanged() 的代码

override fun onResume() {
super.onResume()
if (rv.adapter != null)
(rv.adapter as MyAdapter).apply {
fontSize = Options.getFontSize()
notifyDataSetChanged()
}
}

最佳答案

预计当 notifyDataSetChanged 调用时,整个 View 将被刷新。当您返回 fragment onResume 时,随后您的 notifyDataSetChanged 也会被调用。这就是您看到第一项的原因。

因此,为防止这种情况,您需要在整个数据更改或需要更新时调用 notifyDataSetChanged

我可以给你一些建议。

从 onResume 中删除 notifyDataSetChanged 并使用 diffUtil 更新您的 recyclerView 数据。它只会更新您更改的项目。仅在必要时更新您的数据,例如,如果您详细更新任何数据并希望在列表中更新,您可以覆盖 onActivityResult 并在那里通知您的列表。或者您可以发送广播并在您的列表 fragment 中接收它并通知您列表。

在此先感谢,希望这会有所帮助。

关于android - RecyclerView 在调用 notifyDataSetChanged() 时跳到顶部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59442318/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com