使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
尝试使用 Compose 方式
Jetpack Compose 是推荐用于 Android 的界面工具包。了解如何在 Compose 中使用布局。
您可以自定义 RecyclerView
对象,以满足您的特定需求。使用 RecyclerView 创建动态列表中介绍的标准类提供了大多数开发者所需的全部功能。在许多情况下,您只需要为每个视图持有者设计视图,然后编写代码以使用适当的数据更新这些视图。不过,如果您的应用有特定要求,您可以通过多种方式修改标准行为。本文档介绍了您可以进行的一些自定义。
修改布局
RecyclerView
使用布局管理器将各项内容放置在屏幕上,并确定何时重复使用不再对用户可见的项目视图。为了重复使用(或循环使用)视图,布局管理器可能会让适配器使用数据集中的不同元素替换视图的内容。以这种方式回收视图可避免创建不必要的视图或进行代价高昂的 findViewById()
查找,从而提高性能。Android 支持库包含三个标准布局管理器,每个管理器都提供了许多自定义选项:
如果这些布局管理器不符合您的需求,您可以通过扩展 RecyclerView.LayoutManager
抽象类来创建自己的布局管理器。
为列表项添加动画
每当某个项发生变化时,RecyclerView
都会使用 animator 来更改其外观。该 animator 是扩展抽象 RecyclerView.ItemAnimator
类的对象。默认情况下,RecyclerView
使用 DefaultItemAnimator
来提供动画。如果您想提供自定义动画,可以通过扩展 RecyclerView.ItemAnimator
来定义自己的 animator 对象。
启用列表项选择
借助 recyclerview-selection
库,用户可以通过触摸或鼠标输入来选择 RecyclerView
列表中的项。这样,您仍然可以控制所选项的视觉呈现效果。您也仍然可以控制用于约束选择行为的政策,例如哪些项符合入选条件以及可以选择的项数。
如需为 RecyclerView
实例添加对选择操作的支持,请按以下步骤操作:
- 确定要使用的选择键类型,然后构建
ItemKeyProvider
。
您可以使用以下三种主要类型来标识所选商品:
如需详细了解选择键类型,请参阅 SelectionTracker.Builder
。
- 实现
ItemDetailsLookup
。
ItemDetailsLookup
使选择功能库能够访问给定 MotionEvent
对应的 RecyclerView
项的相关信息。它实际上是由 RecyclerView.ViewHolder
实例支持(或从中提取)的 ItemDetails
实例的工厂。
- 更新
RecyclerView
中的 View
对象,以反映用户是否选择了它们。
选择功能库不会为所选项提供默认视觉装饰。您必须在实现 onBindViewHolder()
时提供此设置。
我们建议您采取以下方法:
- 使用
ActionMode
为用户提供对所选项执行操作所需的工具。
注册 SelectionTracker.SelectionObserver
以在选择状态有变时接收通知。首次选择时,请启动 ActionMode
以向用户表示这一点,并提供特定于该选择的操作。例如,您可以向 ActionMode
栏添加删除按钮,然后将栏上的返回箭头连接到取消选择的操作。当选择列表变空时(如果用户取消选择最后一项),终止操作模式。
- 执行任何经过解释的次级操作。
在事件处理流水线的最后,库可能会判断用户试图通过点按某个项来激活它或试图拖放某个项或一组选定项。请通过注册适当的监听器来回应这些解释。如需了解详情,请参阅 SelectionTracker.Builder
。
- 使用
SelectionTracker.Builder
汇编所有内容。
以下示例展示了如何将这些部分组合在一起:
Kotlin
var tracker = SelectionTracker.Builder(
"my-selection-id",
recyclerView,
StableIdKeyProvider(recyclerView),
MyDetailsLookup(recyclerView),
StorageStrategy.createLongStorage())
.withOnItemActivatedListener(myItemActivatedListener)
.build()
Java
SelectionTracker tracker = new SelectionTracker.Builder<>(
"my-selection-id",
recyclerView,
new StableIdKeyProvider(recyclerView),
new MyDetailsLookup(recyclerView),
StorageStrategy.createLongStorage())
.withOnItemActivatedListener(myItemActivatedListener)
.build();
为了构建 SelectionTracker
实例,您的应用必须向 SelectionTracker.Builder
提供您之前初始化 RecyclerView
时所用的同一个 RecyclerView.Adapter
。因此,创建 SelectionTracker
实例后,请将其注入到 RecyclerView.Adapter
中。否则,您将无法通过 onBindViewHolder()
方法检查某个项的已选中状态。
- 将选中状态包含到 activity 生命周期事件中。
为了在不同的 activity 生命周期事件之间保留选中状态,您的应用必须分别从 activity 的 onSaveInstanceState()
和 onRestoreInstanceState()
方法调用选择状态跟踪器的 onSaveInstanceState()
和 onRestoreInstanceState()
方法。您的应用还必须向 SelectionTracker.Builder
构造函数提供唯一的选择 ID。此 ID 是必需的,因为 activity 或 fragment 可能具有多个不同的可选择列表,而所有这些列表都需要保持其已保存的状态。
其他资源
如需了解详情,请参阅以下参考资料。
本页面上的内容和代码示例受内容许可部分所述许可的限制。Java 和 OpenJDK 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):2025-08-21。
[[["易于理解","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"]],["最后更新时间 (UTC):2025-08-21。"],[],[],null,["# Customize a dynamic list\nPart of [Android Jetpack](/jetpack).\n=============================================================\n\nTry the Compose way \nJetpack Compose is the recommended UI toolkit for Android. Learn how to work with layouts in Compose. \n[Lazy Lists and Grids →](/jetpack/compose/lists#lazy) \n\nYou can customize\n[RecyclerView](/reference/androidx/recyclerview/widget/RecyclerView)\nobjects to meet your specific needs. The standard classes described in\n[Create dynamic lists with\nRecyclerView](/guide/topics/ui/layout/recyclerview) provide all the functionality that most developers need. In\nmany cases, you only need to design the view for each view holder and write the\ncode to update those views with the appropriate data. However, if your app has\nspecific requirements, you can modify the standard behavior in a number of ways.\nThis document describes some of the possible customizations.\n\nModify the layout\n-----------------\n\n`RecyclerView` uses a layout manager to position the individual\nitems on the screen and to determine when to reuse item views that are no longer\nvisible to the user. To reuse---or *recycle* ---a view, a layout\nmanager might ask the adapter to replace the contents of the view with a\ndifferent element from the dataset. Recycling views this way improves\nperformance by avoiding the creation of unnecessary views or performing\nexpensive\n[findViewById()](/reference/android/app/Activity#findViewById(int))\nlookups. The Android Support Library includes three standard layout managers,\nach of which offers many customization options:\n\n- [LinearLayoutManager](/reference/androidx/recyclerview/widget/LinearLayoutManager): arranges the items in a one-dimensional list. Using a `RecyclerView` with `LinearLayoutManager` provides functionality like a [ListView](/reference/android/widget/ListView) layout.\n- [GridLayoutManager](/reference/androidx/recyclerview/widget/GridLayoutManager): arranges the items in a two-dimensional grid, like the squares on a checkerboard. Using a `RecyclerView` with `GridLayoutManager` provides functionality like a [GridView](/reference/android/widget/GridView) layout.\n- [StaggeredGridLayoutManager](/reference/androidx/recyclerview/widget/StaggeredGridLayoutManager): arranges the items in a two-dimensional grid, with each column slightly offset from the one before, like the stars on an American flag.\n\nIf these layout managers don't suit your needs, you can create your own by\nextending the\n[RecyclerView.LayoutManager](/reference/androidx/recyclerview/widget/RecyclerView.LayoutManager)\nabstract class.\n\nAdd item animations\n-------------------\n\nWhenever an item changes, `RecyclerView` uses an *animator*\nto change its appearance. This animator is an object that extends the abstract\n[RecyclerView.ItemAnimator](/reference/androidx/recyclerview/widget/RecyclerView.ItemAnimator)\nclass. By default, the `RecyclerView` uses\n[DefaultItemAnimator](/reference/androidx/recyclerview/widget/DefaultItemAnimator)\nto provide the animation. If you want to provide custom animations, you can\ndefine your own animator object by extending\n`RecyclerView.ItemAnimator`.\n\nEnable list-item selection\n--------------------------\n\nThe\n[`recyclerview-selection`](/reference/androidx/recyclerview/selection/package-summary)\nlibrary lets users select items in a `RecyclerView` list using touch\nor mouse input. This lets you retain control over the visual presentation of a\nselected item. You can also retain control over policies controlling selection\nbehavior, such as which items are eligible for selection and how many items can\nbe selected.\n\nTo add selection support to a `RecyclerView` instance, follow\nthese steps:\n\n1. Determine which selection key type to use, then build an [`ItemKeyProvider`](/reference/androidx/recyclerview/selection/ItemKeyProvider).\n\n There are three key types you can use to identify selected items:\n - [Parcelable](/reference/android/os/Parcelable) and its subclasses, like [Uri](/reference/android/net/Uri)\n - [String](/reference/java/lang/String)\n - [Long](/reference/java/lang/Long)\n\n For detailed information about selection-key types, see\n [SelectionTracker.Builder](/reference/androidx/recyclerview/selection/SelectionTracker.Builder).\n2. Implement [ItemDetailsLookup](/reference/androidx/recyclerview/selection/ItemDetailsLookup).\n3. `ItemDetailsLookup` lets the selection library access information about `RecyclerView` items given a [MotionEvent](/reference/android/view/MotionEvent). It is effectively a factory for [`ItemDetails`](/reference/androidx/recyclerview/selection/ItemDetailsLookup.ItemDetails) instances that are backed up by, or extracted from, a [RecyclerView.ViewHolder](/reference/androidx/recyclerview/widget/RecyclerView.ViewHolder) instance.\n4. Update item [View](/reference/android/view/View) objects in the `RecyclerView` to reflect whether the user selects or unselects them.\n\n The selection library doesn't provide a default visual decoration for the\n selected items. Provide this when you implement\n [onBindViewHolder()](/reference/androidx/recyclerview/widget/RecyclerView.Adapter#onBindViewHolder(VH, int)).\n We recommend the following approach:\n - In `onBindViewHolder()`, call [setActivated()](/reference/android/view/View#setActivated(boolean))---**not** [setSelected()](/reference/android/view/View#setSelected(boolean))---on the `View` object with `true` or `false`, depending on whether the item is selected.\n - Update the styling of the view to represent the activated status. We recommend using a [color state\n list resource](/guide/topics/resources/color-list-resource) to configure the styling.\n5. Use [ActionMode](/reference/androidx/appcompat/view/ActionMode) to provide the user with tools to perform an action on the selection.\n6. Register a [SelectionTracker.SelectionObserver](/reference/androidx/recyclerview/selection/SelectionTracker.SelectionObserver) to be notified when a selection changes. When a selection is first created, start `ActionMode` to present this to the user and provide selection-specific actions. For example, you can add a delete button to the `ActionMode` bar and connect the back arrow on the bar to clear the selection. When the selection becomes empty---if the user clears the selection the last time---terminate action mode.\n7. Perform any interpreted secondary actions.\n8. At the end of the event processing pipeline, the library might determine that the user is attempting to activate an item, by tapping it, or is attempting to drag an item or set of selected items. React to these interpretations by registering the appropriate listener. For more information, see [SelectionTracker.Builder](/reference/androidx/recyclerview/selection/SelectionTracker.Builder).\n9. Assemble everything with `SelectionTracker.Builder`.\n10. The following example shows how to put these pieces together: \n\n### Kotlin\n\n```kotlin\n var tracker = SelectionTracker.Builder(\n \"my-selection-id\",\n recyclerView,\n StableIdKeyProvider(recyclerView),\n MyDetailsLookup(recyclerView),\n StorageStrategy.createLongStorage())\n .withOnItemActivatedListener(myItemActivatedListener)\n .build()\n \n```\n\n### Java\n\n```java\n SelectionTracker tracker = new SelectionTracker.Builder\u003c\u003e(\n \"my-selection-id\",\n recyclerView,\n new StableIdKeyProvider(recyclerView),\n new MyDetailsLookup(recyclerView),\n StorageStrategy.createLongStorage())\n .withOnItemActivatedListener(myItemActivatedListener)\n .build();\n \n```\n11. To build a [SelectionTracker](/reference/androidx/recyclerview/selection/SelectionTracker) instance, your app must supply the same [RecyclerView.Adapter](/reference/androidx/recyclerview/widget/RecyclerView.Adapter) that you use to initialize `RecyclerView` to `SelectionTracker.Builder`. For this reason, after you create the `SelectionTracker` instance, inject it into your `RecyclerView.Adapter`. Otherwise, you can't check an item's selected status from the `onBindViewHolder()` method.\n12. Include selection in the [activity\n lifecycle](/guide/components/activities/activity-lifecycle) events.\n13. To preserve selection state across the activity lifecycle events, your app must call the selection tracker's [onSaveInstanceState()](/reference/androidx/recyclerview/selection/SelectionTracker#onSaveInstanceState(android.os.Bundle)) and [onRestoreInstanceState()](/reference/androidx/recyclerview/selection/SelectionTracker#onRestoreInstanceState(android.os.Bundle)) methods from the activity's [onSaveInstanceState()](/reference/android/app/Activity#onSaveInstanceState(android.os.Bundle)) and [onRestoreInstanceState()](/reference/android/app/Activity#onRestoreInstanceState(android.os.Bundle)) methods, respectively. Your app must also supply a unique selection ID to the `SelectionTracker.Builder` constructor. This ID is required because an activity or a fragment might have more than one distinct, selectable list, all of which need to be persisted in their saved state.\n\nAdditional resources\n--------------------\n\nSee the following references for additional information.\n\n- [Sunflower\n demo app](https://github.com/googlesamples/android-sunflower), which uses `RecyclerView`.\n- [Use\n RecyclerView to display a scrollable list](/codelabs/basic-android-kotlin-training-recyclerview-scrollable-list#0) codelab.\n- [Android\n Kotlin Fundamentals: RecyclerView fundamentals](/codelabs/kotlin-android-training-recyclerview-fundamentals) codelab."]]