จัดการสถานะ 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
เพื่อบันทึกการเปลี่ยนแปลงข้อความ ภายใน callback ให้กําหนดข้อมูลที่จะบันทึก ดังนี้
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 UTC
[[["เข้าใจง่าย","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 UTC"],[],[],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)"]]