管理 RecyclerView 狀態
透過集合功能整理內容
你可以依據偏好儲存及分類內容。
RecyclerView
可利用極少量圖像資源顯示大量資料。當使用者捲動瀏覽 RecyclerView
中的項目時,系統會重複使用捲動至螢幕外項目的 View
例項,以在螢幕上捲動時建立新項目。不過,設定變更 (例如裝置旋轉) 可能會重設 RecyclerView
的狀態,導致使用者必須再次捲動回項目清單中的先前位置。
每當設定變更時,RecyclerView
都應維持原本的狀態 (尤其是捲動位置),清單元素的狀態也不應變動。
維持狀態
設定 RecyclerView.Adapter
的狀態還原政策,儲存 RecyclerView
捲動位置。接著儲存 RecyclerView
清單項目的狀態。然後將清單項目的狀態新增至 RecyclerView
轉接程式,並在清單項目繫結至 ViewHolder
時還原清單項目狀態。
1. 啟用 Adapter
狀態還原政策
啟用 RecyclerView
轉接程式的狀態還原政策,以便在任何設定變更時保留 RecyclerView
的捲動位置。請將政策規格新增至轉接程式建構函式:
Kotlin
class MyAdapter() : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
init {
stateRestorationPolicy = StateRestorationPolicy.PREVENT_WHEN_EMPTY
}
...
}
Java
class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
public Adapter() {
setStateRestorationPolicy(StateRestorationPolicy.PREVENT_WHEN_EMPTY);
}
...
}
2. 儲存有狀態清單項目的狀態
儲存複雜 RecyclerView
清單項目的狀態,例如包含 EditText
元素的項目。舉例來說,如要儲存 EditText
的狀態,請新增與 onClick
處理常式類似的回呼,以擷取文字變更。然後在回呼中,定義要儲存的資料:
Kotlin
input.addTextChangedListener(
afterTextChanged = { text ->
text?.let {
// Save state here.
}
}
)
Java
input.addTextChangedListener(new TextWatcher() {
...
@Override
public void afterTextChanged(Editable s) {
// Save state here.
}
});
在 Activity
或 Fragment
中宣告回呼。使用 ViewModel
儲存狀態。
3. 將清單項目狀態新增至 Adapter
將清單項目的狀態新增至 RecyclerView.Adapter
。請在主機 Activity
或 Fragment
建立時,將項目狀態傳遞至轉接程式建構函式:
Kotlin
val adapter = MyAdapter(items, viewModel.retrieveState())
Java
MyAdapter adapter = new MyAdapter(items, viewModel.retrieveState());
4. 在轉接程式的 ViewHolder
中復原清單項目狀態
在 RecyclerView.Adapter
中,如果您將 ViewHolder
繫結至項目,請還原該項目的狀態:
Kotlin
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
...
val item = items[position]
val state = states.firstOrNull { it.item == item }
if (state != null) {
holder.restore(state)
}
}
Java
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
...
Item item = items[position];
Arrays.stream(states).filter(state -> state.item == item)
.findFirst()
.ifPresent(state -> holder.restore(state));
}
重點
結果
RecyclerView
現在可以還原其捲動位置,以及 RecyclerView
清單中各項目的狀態。
包含此指南的集合
本指南是精選的快速指南系列之一,涵蓋更廣泛的 Android 開發目標:
針對大螢幕進行最佳化
讓應用程式支援平板電腦、折疊式裝置和 ChromeOS 裝置的最佳使用者體驗。
這個頁面中的內容和程式碼範例均受《內容授權》中的授權所規範。Java 與 OpenJDK 是 Oracle 和/或其關係企業的商標或註冊商標。
上次更新時間:2025-02-06 (世界標準時間)。
[[["容易理解","easyToUnderstand","thumb-up"],["確實解決了我的問題","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["缺少我需要的資訊","missingTheInformationINeed","thumb-down"],["過於複雜/步驟過多","tooComplicatedTooManySteps","thumb-down"],["過時","outOfDate","thumb-down"],["翻譯問題","translationIssue","thumb-down"],["示例/程式碼問題","samplesCodeIssue","thumb-down"],["其他","otherDown","thumb-down"]],["上次更新時間:2025-02-06 (世界標準時間)。"],[],[],null,["# Manage RecyclerView state\n\n\u003cbr /\u003e\n\n[`RecyclerView`](/reference/kotlin/androidx/recyclerview/widget/RecyclerView) can display large amounts of data using minimal graphical\nresources. As users scroll through the items in a `RecyclerView`, `View`\ninstances of items that have scrolled off screen are reused to create new items\nas they scroll on screen. But configuration changes, such as device rotation,\ncan reset the state of a `RecyclerView`, forcing users to again scroll to their\nprevious position in the list of items.\n\n`RecyclerView` should maintain its state---in particular, scroll\nposition---and the state of its list elements during all configuration\nchanges.\n\nMaintain state\n--------------\n\nSet the state restoration policy of the `RecyclerView.Adapter` to save the\n`RecyclerView` scroll position. Save the state of `RecyclerView` list items. Add\nthe state of the list items to the `RecyclerView` adapter, and restore the state\nof list items when they're bound to a `ViewHolder`.\n\n### 1. Enable `Adapter` state restoration policy\n\nEnable the state restoration policy of the `RecyclerView` adapter so that the\nscrolling position of the `RecyclerView` is maintained across configuration\nchanges. Add the policy specification to the adapter constructor: \n\n### Kotlin\n\n```kotlin\nclass MyAdapter() : RecyclerView.Adapter\u003cRecyclerView.ViewHolder\u003e() {\n init {\n stateRestorationPolicy = StateRestorationPolicy.PREVENT_WHEN_EMPTY\n }\n ...\n}\n```\n\n### Java\n\n```java\nclass MyAdapter extends RecyclerView.Adapter\u003cRecyclerView.ViewHolder\u003e {\n\n public Adapter() {\n setStateRestorationPolicy(StateRestorationPolicy.PREVENT_WHEN_EMPTY);\n }\n ...\n}\n```\n\n### 2. Save the state of stateful list items\n\nSave the state of complex `RecyclerView` list items, such as items that contain\n`EditText` elements. For example, to save the state of an `EditText`, add a\ncallback similar to an `onClick` handler to capture text changes. Within the\ncallback, define what data to save: \n\n### Kotlin\n\n```kotlin\ninput.addTextChangedListener(\n afterTextChanged = { text -\u003e\n text?.let {\n // Save state here.\n }\n }\n)\n```\n\n### Java\n\n```java\ninput.addTextChangedListener(new TextWatcher() {\n\n ...\n\n @Override\n public void afterTextChanged(Editable s) {\n // Save state here.\n }\n});\n```\n\nDeclare the callback in your `Activity` or `Fragment`. Use a `ViewModel` to\nstore the state.\n\n### 3. Add list item state to the `Adapter`\n\nAdd the state of list items to your `RecyclerView.Adapter`. Pass the item state\nto the adapter constructor when your host `Activity` or `Fragment` is created: \n\n### Kotlin\n\n```kotlin\nval adapter = MyAdapter(items, viewModel.retrieveState())\n```\n\n### Java\n\n```java\nMyAdapter adapter = new MyAdapter(items, viewModel.retrieveState());\n```\n\n### 4. Recover list item state in the adapter's `ViewHolder`\n\nIn the `RecyclerView.Adapter`, when you bind a [`ViewHolder`](/reference/kotlin/androidx/recyclerview/widget/RecyclerView.ViewHolder) to an item,\nrestore the item's state: \n\n### Kotlin\n\n```kotlin\noverride fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {\n ...\n val item = items[position]\n val state = states.firstOrNull { it.item == item }\n\n if (state != null) {\n holder.restore(state)\n }\n}\n```\n\n### Java\n\n```java\n@Override\npublic void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {\n ...\n Item item = items[position];\n Arrays.stream(states).filter(state -\u003e state.item == item)\n .findFirst()\n .ifPresent(state -\u003e holder.restore(state));\n}\n```\n\nKey points\n----------\n\n- [`RecyclerView.Adapter#setStateRestorationPolicy()`](/reference/kotlin/androidx/recyclerview/widget/RecyclerView.Adapter.StateRestorationPolicy): Specifies how a `RecyclerView.Adapter` restores its state after a configuration change.\n- [`ViewModel`](/reference/kotlin/androidx/lifecycle/ViewModel): Holds state for an activity or fragment.\n\nResults\n-------\n\nYour `RecyclerView` is now able to restore its scroll position and the state of\nevery item in the `RecyclerView` list.\n\nCollections that contain this guide\n-----------------------------------\n\nThis guide is part of these curated Quick Guide collections that cover broader\nAndroid development goals: \n\n### Optimize for large screens\n\nEnable your app to support an optimized user experience on tablets, foldables, and ChromeOS devices. \n[Quick guide collection](/quick-guides/collections/optimize-for-large-screens) \n\nHave questions or feedback\n--------------------------\n\nGo to our frequently asked questions page and learn about quick guides or reach out and let us know your thoughts. \n[Go to FAQ](/quick-guides/faq) [Leave feedback](https://issuetracker.google.com/issues/new?component=1573691&template=1993320)"]]