透過集合功能整理內容
你可以依據偏好儲存及分類內容。
試試 Compose
Jetpack Compose 是 Android 推薦的 UI 工具包。瞭解如何在 Compose 中處理版面配置。
您可以依據特定需求自訂 RecyclerView
物件。使用 RecyclerView 建立動態清單中介紹的標準類別,提供了大部分開發人員需要的所有功能。在許多情況下,您只需要為每個檢視區塊擁有者設計檢視區塊,然後撰寫程式碼來使用適當的資料更新這些檢視區塊。不過,如果您的應用程式有特定要求,則可以透過多種方式修改標準行為。本文將說明一些可能的自訂項目。
修改版面配置
RecyclerView
會使用版面配置管理員確定個別項目在螢幕上的擺放位置,並決定何時重複使用對使用者不再顯示的項目檢視區塊。如要重複使用 (或回收利用) 檢視區塊,版面配置管理員可能會要求調整器將檢視區塊的內容替換成資料集中的另一元素。以這種方式回收利用檢視區塊,能夠避免建立不必要的檢視區塊或執行昂貴的 findViewById()
查詢,從而提升效能。Android 支援資料庫包含三個標準版面配置管理員,每個管理員都提供多個自訂選項:
如果上述版面配置管理員都不符合您的需求,則可以擴充 RecyclerView.LayoutManager
抽象類別,建立自己的版面配置管理員。
新增項目動畫
當項目變更時,RecyclerView
會使用動畫工具來變更其外觀。這個動畫工具是可擴充抽象 RecyclerView.ItemAnimator
類別的物件。根據預設,RecyclerView
會使用 DefaultItemAnimator
提供動畫。如要提供自訂動畫,可以擴充 RecyclerView.ItemAnimator
來定義自己的動畫工具物件。
啟用清單項目選取內容
recyclerview-selection
程式庫可讓使用者透過輕觸或滑鼠輸入的方式,選取 RecyclerView
清單中的項目。您可以控管所選項目的視覺呈現方式,也可以控管用來控制選取行為的政策,例如能夠選取的項目以及可選取的項目數。
如要向 RecyclerView
例項新增選取支援,請按照以下步驟操作:
- 確定要使用的選取索引鍵類型,然後建構
ItemKeyProvider
。您可以使用三種主要類型來識別所選項目:
如要進一步瞭解選取索引鍵類型,請參閱 SelectionTracker.Builder
。
- 實作
ItemDetailsLookup
。
ItemDetailsLookup
讓選取程式庫能夠存取提供 MotionEvent
的 RecyclerView
項目相關資訊。這實際上是 ItemDetails
例項的工廠,這些例項由 RecyclerView.ViewHolder
例項備份 (或從中擷取而來)。
- 更新
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
例項,應用程式提供的 RecyclerView.Adapter
必須與用於將 RecyclerView
初始化為 SelectionTracker.Builder
的工具相同。因此,建立 SelectionTracker
例項後,請將該例項插入 RecyclerView.Adapter
。否則,您將無法使用 onBindViewHolder()
方法查看該項目的所選狀態。
- 將選取內容加入活動生命週期事件中。
如要在活動生命週期事件中保留選取狀態,應用程式必須分別從活動的 onSaveInstanceState()
和 onRestoreInstanceState()
方法,呼叫選取追蹤工具的 onSaveInstanceState()
和 onRestoreInstanceState()
方法。您的應用程式還必須向 SelectionTracker.Builder
建構函式提供專屬的選取 ID。由於活動或片段可能擁有多個不同的可選取清單,所有這些清單都需要保持儲存狀態,因此需要提供這一 ID。
其他資源
詳情請參閱下列參考資料。
這個頁面中的內容和程式碼範例均受《內容授權》中的授權所規範。Java 與 OpenJDK 是 Oracle 和/或其關係企業的商標或註冊商標。
上次更新時間:2025-08-27 (世界標準時間)。
[[["容易理解","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-08-27 (世界標準時間)。"],[],[],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."]]