
- 1.2.0-alpha02 版本https://developer.android.google.cn/jetpack/androidx/releases/recyclerview
恢復至原有滾動位置
有好幾種方法可以用來恢復 RecyclerView 至正確的滾動位置,您可能已經在實際項目中用到了這些方法。其中最好的一種方法是將數據提前緩存在內存、ViewModel 或 Repository 中,然后確保在第一次布局傳入之前,將緩存的數據設置到 Adapter 中去。如果根據您的項目實際情況無法采用這種方法,那也可以使用其他的方法,只是要么比較復雜 (比如避免在 RecyclerView 中設置 Adapter,但這樣又有可能導致像 header 等 item 的顯示問題),要么會導致 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 方法,來允許您設置它的狀態恢復策略 (通過枚舉類型 StateRestorationPolicy)。它有三個選項:
ALLOW — 默認狀態,會在下一次布局完成時立即恢復 RecyclerView 狀態;
PREVENT_WHEN_EMPTY — 僅當 adapter 不為空 (即 adapter.getItemCount() > 0) 的時候,才恢復 RecyclerView 的狀態。如果您是異步加載數據,RecyclerView 會等待數據加載完畢之后,才對狀態進行恢復。如果在 Adapter 中有一些默認的 item,比如 header 或是 load progress indicator,那您應該使用 PREVENT 選項,除非是通過 ConcatAdapter 添加默認的 item,了解更多詳細信息,請查閱《使用 ConcatAdapter 順序連接其他 Adapter》。ConcatAdapter 會等待所有的 adapter 全部準備就緒后,才進行狀態的恢復;
PREVENT — 所有的狀態恢復都會等到您設置了 ALLOW 或者 PREVENT_WHEN_EMPTY 選項,才會得到執行。
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
通過如下示例代碼可設置 adapter 的狀態恢復策略:
adapter.stateRestorationPolicy = PREVENT_WHEN_EMPTY
通過這篇短小精悍的文章您可以了解到關于 RecyclerView 的延遲狀態恢復 (lazy state restoration) 功能。趕快開始使用吧!
推薦閱讀



