recyclerview 加载fragment_恢复 RecyclerView 的滚动位置
- 1.2.0-alpha02 版本https://developer.android.google.cn/jetpack/androidx/releases/recyclerview
恢復(fù)至原有滾動位置
有好幾種方法可以用來恢復(fù) RecyclerView 至正確的滾動位置,您可能已經(jīng)在實(shí)際項(xiàng)目中用到了這些方法。其中最好的一種方法是將數(shù)據(jù)提前緩存在內(nèi)存、ViewModel 或 Repository 中,然后確保在第一次布局傳入之前,將緩存的數(shù)據(jù)設(shè)置到 Adapter 中去。如果根據(jù)您的項(xiàng)目實(shí)際情況無法采用這種方法,那也可以使用其他的方法,只是要么比較復(fù)雜 (比如避免在 RecyclerView 中設(shè)置 Adapter,但這樣又有可能導(dǎo)致像 header 等 item 的顯示問題),要么會導(dǎo)致 LayoutManager.onRestoreInstanceState API被濫用。LayoutManager.onRestoreInstanceState
https://developer.android.google.cn/reference/androidx/recyclerview/widget/RecyclerView.LayoutManager?hl=en#onRestoreInstanceState(android.os.Parcelable)
recyclerview:1.2.0-alpha02 版本中提供的解決方案是引入一個新的 Adapter 方法,來允許您設(shè)置它的狀態(tài)恢復(fù)策略 (通過枚舉類型 StateRestorationPolicy)。它有三個選項(xiàng):
ALLOW — 默認(rèn)狀態(tài),會在下一次布局完成時立即恢復(fù) RecyclerView 狀態(tài);
PREVENT_WHEN_EMPTY — 僅當(dāng) adapter 不為空 (即 adapter.getItemCount() > 0) 的時候,才恢復(fù) RecyclerView 的狀態(tài)。如果您是異步加載數(shù)據(jù),RecyclerView 會等待數(shù)據(jù)加載完畢之后,才對狀態(tài)進(jìn)行恢復(fù)。如果在 Adapter 中有一些默認(rèn)的 item,比如 header 或是 load progress indicator,那您應(yīng)該使用 PREVENT 選項(xiàng),除非是通過 ConcatAdapter 添加默認(rèn)的 item,了解更多詳細(xì)信息,請查閱《使用 ConcatAdapter 順序連接其他 Adapter》。ConcatAdapter 會等待所有的 adapter 全部準(zhǔn)備就緒后,才進(jìn)行狀態(tài)的恢復(fù);
PREVENT — 所有的狀態(tài)恢復(fù)都會等到您設(shè)置了 ALLOW 或者 PREVENT_WHEN_EMPTY 選項(xiàng),才會得到執(zhí)行。
StateRestorationPolicy
https://developer.android.google.cn/reference/androidx/recyclerview/widget/RecyclerView.Adapter.StateRestorationPolicy
ALLOW
https://developer.android.google.cn/reference/androidx/recyclerview/widget/RecyclerView.Adapter.StateRestorationPolicy#ALLOW
PREVENT_WHEN_EMPTY
https://developer.android.google.cn/reference/androidx/recyclerview/widget/RecyclerView.Adapter.StateRestorationPolicy#PREVENT_WHEN_EMPTY
ConcatAdapter
https://developer.android.google.cn/reference/androidx/recyclerview/widget/ConcatAdapter
PREVENT
https://developer.android.google.cn/reference/androidx/recyclerview/widget/RecyclerView.Adapter.StateRestorationPolicy#PREVENT
通過如下示例代碼可設(shè)置 adapter 的狀態(tài)恢復(fù)策略:
adapter.stateRestorationPolicy = PREVENT_WHEN_EMPTY通過這篇短小精悍的文章您可以了解到關(guān)于 RecyclerView 的延遲狀態(tài)恢復(fù) (lazy state restoration) 功能。趕快開始使用吧!推薦閱讀
?點(diǎn)擊屏末?|?閱讀原文?|?使用 RecyclerView 創(chuàng)建列表總結(jié)
以上是生活随笔為你收集整理的recyclerview 加载fragment_恢复 RecyclerView 的滚动位置的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: (转)SQL Server:在 SQL
- 下一篇: 4412 字符类设备的设备号