إدارة حالة 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
، أضِف دالّة callback مشابهة لمعالج 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)"]]