컬렉션을 사용해 정리하기
내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요.
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
항목에 관한 정보에 액세스할 수 있습니다.
이는 사실상 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()
자바
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는 필수입니다.
추가 리소스
자세한 내용은 다음 참고 자료를 참고하세요.
이 페이지에 나와 있는 콘텐츠와 코드 샘플에는 콘텐츠 라이선스에서 설명하는 라이선스가 적용됩니다. 자바 및 OpenJDK는 Oracle 및 Oracle 계열사의 상표 또는 등록 상표입니다.
최종 업데이트: 2025-08-27(UTC)
[[["이해하기 쉬움","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(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."]]