コレクションでコンテンツを整理
必要に応じて、コンテンツの保存と分類を行います。
Compose をお試しください
Jetpack Compose は、Android で推奨される UI ツールキットです。Compose でレイアウトを扱う方法について説明します。
特定のニーズに合わせて RecyclerView
オブジェクトをカスタマイズできます。RecyclerView でダイナミック リストを作成するで説明した標準のクラスでは、ほとんどのデベロッパーが必要とする機能がすべて用意されています。多くの場合、必要なのは各ビューホルダーのビューを設計し、それらのビューを適切なデータで更新するコードを記述することだけです。ただし、アプリに特定の要件がある場合は、さまざまな方法で標準の動作を変更できます。このドキュメントでは、可能なカスタマイズの一部について説明します。
レイアウトを変更する
RecyclerView
は、レイアウト マネージャーを使用して個々のアイテムを画面上に配置します。また、ユーザーに表示されなくなったアイテムビューを再利用するタイミングを判断します。ビューを再利用(リサイクル)するために、レイアウト マネージャーがアダプターに対し、ビューのコンテンツをデータセットの別の要素で置き換えるよう求めることがあります。この方法でビューをリサイクルすると、不要なビューが作成されず、負荷の高い findViewById()
による検索も行われないため、パフォーマンスが向上します。Android サポート ライブラリには 3 つの標準レイアウト マネージャーが含まれており、それぞれに各種のカスタマイズ オプションが用意されています。
これらのレイアウト マネージャーの中にニーズを満たすものがない場合は、RecyclerView.LayoutManager
抽象クラスを拡張することによって独自のレイアウト マネージャーを作成できます。
アイテム アニメーションを追加する
RecyclerView
はアイテムが変更されるたびに、アニメーターを使用してその外観を変更します。このアニメーターは、RecyclerView.ItemAnimator
抽象クラスを拡張するオブジェクトです。デフォルトでは、RecyclerView
は DefaultItemAnimator
を使用してアニメーションを表示します。カスタムのアニメーションを表示したい場合は、RecyclerView.ItemAnimator
を拡張することによって独自のアニメーター オブジェクトを定義できます。
リストアイテムを選択できるようにする
recyclerview-selection
ライブラリを使用すると、ユーザーがタップまたはマウス入力で RecyclerView
リスト内のアイテムを選択できるようになります。これにより、選択されたアイテムの視覚的な表示に対するコントロールを維持できます。また、選択の動作を管理するポリシー(選択の対象になり得るアイテム、選択可能なアイテムの数など)に対するコントロールも維持できます。
RecyclerView
インスタンスに選択サポートを追加する手順は次のとおりです。
- 使用する選択キーのタイプを決定し、
ItemKeyProvider
を作成します。選択したアイテムを識別するために使用できる主なタイプは 3 つあります。
選択キーのタイプについて詳しくは、SelectionTracker.Builder
をご覧ください。
ItemDetailsLookup
を実装します。
ItemDetailsLookup
を実装すると、MotionEvent
が発生した場合に、RecyclerView
アイテムに関する情報に選択ライブラリからアクセスできるようになります。これは実質的に、RecyclerView.ViewHolder
インスタンスによってバックアップされる(またはこのインスタンスから抽出される)、ItemDetails
インスタンスのファクトリです。
RecyclerView
のアイテム View
オブジェクトを更新し、ユーザーがそれらを選択または選択解除したかどうかを反映します。選択ライブラリには、選択されたアイテムに対するデフォルトの視覚的装飾は用意されていません。onBindViewHolder()
を実装する場合は、視覚的装飾を用意する必要があります。次のアプローチをおすすめします。
ActionMode
を使用して、選択されたアイテムに対するアクションを実行するツールをユーザーに提供します。
選択が変更されたときに通知を受け取るには、SelectionTracker.SelectionObserver
を登録します。アイテムが初めて選択されたときに、ActionMode
を開始してユーザーにそのことを示し、選択に固有のアクションを提供します。たとえば、削除ボタンを 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
を初期化するために使用したのと同じ RecyclerView.Adapter
を SelectionTracker.Builder
に指定する必要があります。そのため、SelectionTracker
インスタンスを作成したら、それを RecyclerView.Adapter
に挿入します。そうしないと、アイテムの選択状態を onBindViewHolder()
メソッドで確認できなくなります。
- 選択をアクティビティのライフサイクル イベントに追加します。
選択状態をアクティビティのライフサイクル イベント間で保持するには、アプリで選択トラッカーの onSaveInstanceState()
メソッドと onRestoreInstanceState()
メソッドをアクティビティの onSaveInstanceState()
メソッドと onRestoreInstanceState()
メソッドからそれぞれ呼び出す必要があります。アプリでは、一意の選択 ID を SelectionTracker.Builder
コンストラクタに提供する必要もあります。この ID は必須です。なぜなら、アクティビティやフラグメントに選択可能なリストが複数ある場合は、それらすべてを保存された状態に維持する必要があるためです。
参考情報
詳細については、以下のリファレンスをご覧ください。
このページのコンテンツやコードサンプルは、コンテンツ ライセンスに記載のライセンスに従います。Java および OpenJDK は Oracle および関連会社の商標または登録商標です。
最終更新日 2025-08-27 UTC。
[null,null,["最終更新日 2025-08-27 UTC。"],[],[],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."]]