Restez organisé à l'aide des collections
Enregistrez et classez les contenus selon vos préférences.
Ce guide s'appuie sur la présentation de la bibliothèque Paging, qui explique comment présenter des listes d'informations aux utilisateurs dans l'interface utilisateur de votre application, en particulier lorsque ces informations changent.
classConcertActivity:AppCompatActivity(){privatevaladapter=ConcertAdapter()// Use the 'by viewModels()' Kotlin property delegate// from the activity-ktx artifactprivatevalviewModel:ConcertViewModelbyviewModels()overridefunonCreate(savedInstanceState:Bundle?){super.onCreate(savedInstanceState);viewModel.concerts.observe(this,Observer{adapter.submitList(it)})}}
Lorsque les sources de données fournissent de nouvelles instances de PagedList, l'activité envoie ces objets à l'adaptateur. L'intégration de PagedListAdapter définit le mode de calcul des mises à jour et gère automatiquement la pagination et la vérification différentielle ("diffing") des listes. ViewHolder ne doit donc être lié qu'à un élément donné :
Kotlin
classConcertAdapter():PagedListAdapter<Concert,ConcertViewHolder>(DIFF_CALLBACK){overridefunonBindViewHolder(holder:ConcertViewHolder,position:Int){valconcert:Concert? =getItem(position)// Note that "concert" is a placeholder if it's null.holder.bindTo(concert)}companionobject{privatevalDIFF_CALLBACK=...// See Implement the diffing callback section.}}
Java
publicclassConcertAdapterextendsPagedListAdapter<Concert,ConcertViewHolder>{protectedConcertAdapter(){super(DIFF_CALLBACK);}@OverridepublicvoidonBindViewHolder(@NonNullConcertViewHolderholder,intposition){Concertconcert=getItem(position);// Note that "concert" can be null if it's a placeholder.holder.bindTo(concert);}privatestaticDiffUtil.ItemCallback<Concert>DIFF_CALLBACK=...// See Implement the diffing callback section.}
Le PagedListAdapter gère les événements de chargement de page à l'aide d'un objet PagedList.Callback. Lorsque l'utilisateur fait défiler la page, PagedListAdapter appelle PagedList.loadAround() pour fournir des indications au PagedList sous-jacent pour savoir quels éléments il doit récupérer à partir de DataSource.
Intégrer le rappel de vérification différentielle ("diffing")
L'exemple suivant montre une intégration manuelle de areContentsTheSame(), qui compare les champs d'objet pertinents :
Kotlin
privatevalDIFF_CALLBACK=object:DiffUtil.ItemCallback<Concert>(){// The ID property identifies when items are the same.overridefunareItemsTheSame(oldItem:Concert,newItem:Concert)=oldItem.id==newItem.id// If you use the "==" operator, make sure that the object implements// .equals(). Alternatively, write custom data comparison logic here.overridefunareContentsTheSame(oldItem:Concert,newItem:Concert)=oldItem==newItem}
Java
privatestaticDiffUtil.ItemCallback<Concert>DIFF_CALLBACK=newDiffUtil.ItemCallback<Concert>(){@OverridepublicbooleanareItemsTheSame(ConcertoldItem,ConcertnewItem){// The ID property identifies when items are the same.returnoldItem.getId()==newItem.getId();}@OverridepublicbooleanareContentsTheSame(ConcertoldItem,ConcertnewItem){// Don't use the "==" operator here. Either implement and use .equals(),// or write custom data comparison logic here.returnoldItem.equals(newItem);}};
Étant donné que votre adaptateur inclut la définition de comparaison d'éléments, il détecte automatiquement les modifications apportées à ces éléments lorsqu'un nouvel objet PagedList est chargé. L'adaptateur déclenche donc des animations d'éléments efficaces dans votre objet RecyclerView.
Diffing à l'aide d'un autre type d'adaptateur
Si vous choisissez de ne pas hériter de PagedListAdapter, par exemple si vous utilisez une bibliothèque fournissant son propre adaptateur, vous pouvez toujours utiliser la fonction de diffing de l'adaptateur de la bibliothèque Paging en travaillant directement avec un objet AsyncPagedListDiffer.
Fournir des espaces réservés dans votre UI
Si vous souhaitez que votre interface utilisateur affiche une liste avant que votre application n'ait fini d'extraire les données, vous pouvez présenter des éléments de liste d'espace réservé à vos utilisateurs. PagedList gère ce cas de figure en marquant les données de l'élément de liste comme null jusqu'à ce qu'elles soient chargées.
Les espaces réservés offrent les avantages suivants :
Compatibilité avec les barres de défilement : la PagedList fournit le nombre d'éléments de liste au PagedListAdapter. Ces informations permettent à l'adaptateur de tracer une barre de défilement qui représente toute la taille de la liste. Lorsque de nouvelles pages se chargent, la barre de défilement ne saute pas, car la taille de votre liste ne change pas.
Aucune icône de chargement requise : la taille de la liste étant déjà connue, il est inutile d'alerter les utilisateurs lorsque d'autres éléments sont en cours de chargement. Les espaces réservés eux-mêmes transmettent cette information.
Avant d'ajouter la prise en charge des espaces réservés, tenez compte des conditions préalables suivantes :
Requiert un ensemble de données dénombrables : les instances de DataSource de la bibliothèque de persistance Room peuvent compter leurs articles de manière efficace. Toutefois, si vous utilisez une solution de stockage local personnalisée ou une architecture de données basée uniquement sur le réseau, il peut se révéler coûteux, voire impossible, de déterminer le nombre d'éléments qui composent votre ensemble de données.
L'adaptateur doit tenir compte des éléments non chargés : l'adaptateur ou le mécanisme de présentation que vous utilisez pour préparer la liste en cas d'augmentation doit gérer les éléments de liste vides. Par exemple, lorsque vous liez des données à un ViewHolder, vous devez fournir des valeurs par défaut pour représenter les données non chargées.
Requiert des vues d'élément de taille identique : si la taille des éléments de la liste peut changer en fonction de leur contenu, comme les mises à jour des réseaux sociaux, le balayage croisé d'éléments n'est pas optimal. Nous vous recommandons alors vivement de désactiver les espaces réservés.
Envoyer un commentaire
Faites-nous part de vos commentaires et de vos idées via les ressources suivantes :
Le contenu et les exemples de code de cette page sont soumis aux licences décrites dans la Licence de contenu. Java et OpenJDK sont des marques ou des marques déposées d'Oracle et/ou de ses sociétés affiliées.
Dernière mise à jour le 2025/07/27 (UTC).
[[["Facile à comprendre","easyToUnderstand","thumb-up"],["J'ai pu résoudre mon problème","solvedMyProblem","thumb-up"],["Autre","otherUp","thumb-up"]],[["Il n'y a pas l'information dont j'ai besoin","missingTheInformationINeed","thumb-down"],["Trop compliqué/Trop d'étapes","tooComplicatedTooManySteps","thumb-down"],["Obsolète","outOfDate","thumb-down"],["Problème de traduction","translationIssue","thumb-down"],["Mauvais exemple/Erreur de code","samplesCodeIssue","thumb-down"],["Autre","otherDown","thumb-down"]],["Dernière mise à jour le 2025/07/27 (UTC)."],[],[],null,["# Display paged lists\n\nThis guide builds upon the [Paging Library\noverview](/topic/libraries/architecture/paging), describing how you can\npresent lists of information to users in your app's UI, particularly when this\ninformation changes.\n| **Caution:** This guide covers an older, deprecated version of the Paging library. For more information about the latest stable version of Paging, see the [Paging\n| 3 guides](/topic/libraries/architecture/paging/v3-overview).\n\nConnect your UI to your view model\n----------------------------------\n\nYou can connect an instance of\n[`LiveData\u003cPagedList\u003e`](/reference/androidx/lifecycle/LiveData) to a\n[`PagedListAdapter`](/reference/androidx/paging/PagedListAdapter), as shown\nin the following code snippet: \n\n### Kotlin\n\n```kotlin\nclass ConcertActivity : AppCompatActivity() {\n private val adapter = ConcertAdapter()\n\n // Use the 'by viewModels()' Kotlin property delegate\n // from the activity-ktx artifact\n private val viewModel: ConcertViewModel by viewModels()\n\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState);\n viewModel.concerts.observe(this, Observer { adapter.submitList(it) })\n }\n}\n```\n\n### Java\n\n```java\npublic class ConcertActivity extends AppCompatActivity {\n private ConcertAdapter adapter = new ConcertAdapter();\n private ConcertViewModel viewModel;\n\n @Override\n public void onCreate(@Nullable Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n viewModel = new ViewModelProvider(this).get(ConcertViewModel.class);\n viewModel.concertList.observe(this, adapter::submitList);\n }\n}\n```\n\nAs data sources provide new instances of\n[`PagedList`](/reference/androidx/paging/PagedList), the activity sends\nthese objects to the adapter. The\n[`PagedListAdapter`](/reference/androidx/paging/PagedListAdapter)\nimplementation defines how updates are computed, and it automatically handles\npaging and list diffing. Therefore, your\n[`ViewHolder`](/reference/androidx/recyclerview/widget/RecyclerView.ViewHolder)\nonly needs to bind to a particular provided item: \n\n### Kotlin\n\n```kotlin\nclass ConcertAdapter() :\n PagedListAdapter\u003cConcert, ConcertViewHolder\u003e(DIFF_CALLBACK) {\n override fun onBindViewHolder(holder: ConcertViewHolder, position: Int) {\n val concert: Concert? = getItem(position)\n\n // Note that \"concert\" is a placeholder if it's null.\n holder.bindTo(concert)\n }\n\n companion object {\n private val DIFF_CALLBACK = ... // See #implement-diffing-callback section.\n }\n}\n```\n\n### Java\n\n```java\npublic class ConcertAdapter\n extends PagedListAdapter\u003cConcert, ConcertViewHolder\u003e {\n protected ConcertAdapter() {\n super(DIFF_CALLBACK);\n }\n\n @Override\n public void onBindViewHolder(@NonNull ConcertViewHolder holder,\n int position) {\n Concert concert = getItem(position);\n\n // Note that \"concert\" can be null if it's a placeholder.\n holder.bindTo(concert);\n }\n\n private static DiffUtil.ItemCallback\u003cConcert\u003e DIFF_CALLBACK\n = ... // See #implement-diffing-callback section.\n}\n```\n\nThe [`PagedListAdapter`](/reference/androidx/paging/PagedListAdapter)\nhandles page load events using a\n[`PagedList.Callback`](/reference/androidx/paging/PagedList.Callback)\nobject. As the user scrolls, the `PagedListAdapter` calls\n[`PagedList.loadAround()`](/reference/androidx/paging/PagedList#loadaround)\nto provide hints to the underlying\n[`PagedList`](/reference/androidx/paging/PagedList) as to\nwhich items it should fetch from the\n[`DataSource`](/reference/androidx/paging/DataSource).\n| **Note:** [`PagedList`](/reference/androidx/paging/PagedList) is content-immutable. This means that, although new content can be loaded into an instance of `PagedList`, the loaded items themselves cannot change once loaded. As such, if content in a `PagedList` updates, the [`PagedListAdapter`](/reference/androidx/paging/PagedListAdapter) object receives a completely new `PagedList` that contains the updated information.\n\nImplement the diffing callback\n------------------------------\n\nThe following sample shows a manual implementation of\n[`areContentsTheSame()`](/reference/androidx/recyclerview/widget/DiffUtil.ItemCallback#arecontentsthesame),\nwhich compares relevant object fields: \n\n### Kotlin\n\n```kotlin\nprivate val DIFF_CALLBACK = object : DiffUtil.ItemCallback\u003cConcert\u003e() {\n // The ID property identifies when items are the same.\n override fun areItemsTheSame(oldItem: Concert, newItem: Concert) =\n oldItem.id == newItem.id\n\n // If you use the \"==\" operator, make sure that the object implements\n // .equals(). Alternatively, write custom data comparison logic here.\n override fun areContentsTheSame(\n oldItem: Concert, newItem: Concert) = oldItem == newItem\n}\n```\n\n### Java\n\n```java\nprivate static DiffUtil.ItemCallback\u003cConcert\u003e DIFF_CALLBACK =\n new DiffUtil.ItemCallback\u003cConcert\u003e() {\n\n @Override\n public boolean areItemsTheSame(Concert oldItem, Concert newItem) {\n // The ID property identifies when items are the same.\n return oldItem.getId() == newItem.getId();\n }\n\n @Override\n public boolean areContentsTheSame(Concert oldItem, Concert newItem) {\n // Don't use the \"==\" operator here. Either implement and use .equals(),\n // or write custom data comparison logic here.\n return oldItem.equals(newItem);\n }\n};\n```\n\nBecause your adapter includes your definition of comparing items, the adapter\nautomatically detects changes to these items when a new `PagedList` object is\nloaded. As a result, the adapter triggers efficient item animations within your\n`RecyclerView` object.\n\nDiffing using a different adapter type\n--------------------------------------\n\nIf you choose not to inherit from\n[`PagedListAdapter`](/reference/androidx/paging/PagedListAdapter)---such as\nwhen you're using a library that provides its own adapter---you can still use the\nPaging Library adapter's diffing functionality by working directly with an\n[`AsyncPagedListDiffer`](/reference/androidx/paging/AsyncPagedListDiffer)\nobject.\n\nProvide placeholders in your UI\n-------------------------------\n\nIn cases where you want your UI to display a list before your app has finished\nfetching data, you can show placeholder list items to your users. The\n[`PagedList`](/reference/androidx/paging/PagedList) handles this case by\npresenting the list item data as `null` until the data is loaded.\n| **Note:** By default, the Paging Library enables this placeholder behavior.\n\nPlaceholders have the following benefits:\n\n- **Support for scrollbars:** The [`PagedList`](/reference/androidx/paging/PagedList) provides the number of list items to the [`PagedListAdapter`](/reference/androidx/paging/PagedListAdapter). This information allows the adapter to draw a scrollbar that conveys the full size of the list. As new pages load, the scrollbar doesn't jump because your list doesn't change size.\n- **No loading spinner necessary:** Because the list size is already known, there's no need to alert users that more items are loading. The placeholders themselves convey that information.\n\nBefore adding support for placeholders, though, keep the following\npreconditions in mind:\n\n- **Requires a countable data set:** Instances of [`DataSource`](/reference/androidx/paging/DataSource) from the [Room\n persistence library](/topic/libraries/architecture/room) can efficiently count their items. If you're using a custom local storage solution or a [network-only\n data architecture](/topic/libraries/architecture/paging#network-only-data-arch), however, it might be expensive or even impossible to determine how many items comprise your data set.\n- **Requires adapter to account for unloaded items:** The adapter or presentation mechanism that you use to prepare the list for inflation needs to handle null list items. For example, when binding data to a [`ViewHolder`](/reference/androidx/recyclerview/widget/RecyclerView.ViewHolder), you need to provide default values to represent unloaded data.\n- **Requires same-sized item views:** If list item sizes can change based on their content, such as social networking updates, crossfading between items doesn't look good. We strongly suggest disabling placeholders in this case.\n\nProvide feedback\n----------------\n\nShare your feedback and ideas with us through these resources:\n\n[Issue tracker](https://issuetracker.google.com/issues/new?component=413106&template=1096385) :bug:\n: Report issues so we can fix bugs.\n\nAdditional resources\n--------------------\n\nTo learn more about the Paging Library, consult the\nfollowing resources.\n\n### Samples\n\n- [Android Architecture Components Paging\n sample](https://github.com/android/architecture-components-samples/tree/paging2/PagingSample)\n- [Paging With Network Sample](https://github.com/android/architecture-components-samples/tree/paging2/PagingWithNetworkSample)\n\n### Codelabs\n\n- [Android Paging codelab](https://codelabs.developers.google.com/codelabs/android-paging/index.html?index=..%2F..%2Findex#0)\n\n### Videos\n\n- [Android Jetpack: manage infinite lists with RecyclerView and Paging\n (Google I/O '18)](https://www.youtube.com/watch?v=BE5bsyGGLf4)\n- [Android Jetpack: Paging](https://www.youtube.com/watch?v=QVMqCRs0BNA)\n\nRecommended for you\n-------------------\n\n- Note: link text is displayed when JavaScript is off\n- [Paging 2 library overview](/topic/libraries/architecture/paging)\n- [Migrate to Paging 3](/topic/libraries/architecture/paging/v3-migration)\n- [Gather paged data](/topic/libraries/architecture/paging/data)"]]