Создайте список, используя несколько типов элементов.
Оптимизируйте свои подборки
Сохраняйте и классифицируйте контент в соответствии со своими настройками.
Вы можете использовать список с несколькими типами элементов для отображения смешанных типов контента, таких как текст, изображения и интерактивные элементы.
Совместимость версий
Для этой реализации требуется, чтобы в minSDK вашего проекта был установлен уровень API 21 или выше.
Зависимости
Добавить несколько типов элементов
Вы можете указать тип контента для каждого элемента макета при составлении списка или сетки с несколькими типами элементов:
Указывает тип контента для каждого элемента, устанавливая contentType в items() .
Сопоставляет каждый тип контента с соответствующим составным объектом. Например, Audio — это contentType , который определен в другом месте и сопоставлен с составным элементом AudioMessage .
Compose повторно использует визуализированные составные элементы для каждого элемента данного типа контента.
Результаты
Рисунок 1. Вывод кода, показывающий аудио и текстовые сообщения.
Коллекции, содержащие это руководство
Это руководство является частью тщательно подобранной коллекции быстрых руководств, охватывающих более широкие цели разработки Android:
Отобразить список или сетку
Списки и сетки позволяют вашему приложению отображать коллекции в визуально приятной форме, удобной для использования пользователями.
Контент и образцы кода на этой странице предоставлены по лицензиям. Java и OpenJDK – это зарегистрированные товарные знаки корпорации Oracle и ее аффилированных лиц.
Последнее обновление: 2025-02-06 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-02-06 UTC."],[],[],null,["# Build a list using multiple item types\n\n\u003cbr /\u003e\n\nYou can use a list with multiple item types to display mixed content types such\nas text, images, and interactive elements.\n\nVersion compatibility\n---------------------\n\nThis implementation requires that your project minSDK be set to API level 21 or\nhigher.\n\n### Dependencies\n\n### Kotlin\n\n\u003cbr /\u003e\n\n```kotlin\n implementation(platform(\"androidx.compose:compose-bom:2025.08.00\"))\n \n```\n\n\u003cbr /\u003e\n\n### Groovy\n\n\u003cbr /\u003e\n\n```groovy\n implementation platform('androidx.compose:compose-bom:2025.08.00')\n \n```\n\n\u003cbr /\u003e\n\nAdd multiple item types\n-----------------------\n\nYou can specify the content type for each item of the layout when you compose a\nlist or a grid with multiple types of items:\n\n\n```kotlin\n@Composable\nfun ListWithMultipleItems(messages: List\u003cAny\u003e) {\n LazyColumn {\n items(\n messages.size,\n contentType = { it }\n ) {\n for (message in messages)\n when (message) {\n is MediaStore.Audio -\u003e AudioMessage(message)\n is Text -\u003e TextMessage(message)\n }\n }\n }\n}\n\n@Composable\nfun AudioMessage(message: MediaStore.Audio) {\n TODO(\"Not yet implemented.\")\n}\n\n@Composable\nfun TextMessage(message: Text) {\n TODO(\"Not yet implemented.\")\n}\n\ndata class SampleMessage(val text: String, val content: Any)https://github.com/android/snippets/blob/dd30aee903e8c247786c064faab1a9ca8d10b46e/compose/snippets/src/main/java/com/example/compose/snippets/lists/ListWithMultipleItemTypes.kt#L25-L51\n```\n\n\u003cbr /\u003e\n\n### Key points about the code\n\n- Specifies the content type for each item by setting [`contentType`](/reference/kotlin/androidx/compose/foundation/lazy/package-summary#extension-functions-summary) in [`items()`](/reference/kotlin/androidx/compose/foundation/lazy/LazyListScope#items(kotlin.Int,kotlin.Function1,kotlin.Function1,kotlin.Function2)).\n- Maps each content type to a corresponding composable. For example, `Audio` is a `contentType` that is defined elsewhere and is mapped to an `AudioMessage` composable.\n- Compose reuses the rendered composables for each item of a given content type.\n\nResults\n-------\n\n**Figure 1.** Code output showing audio and text messages.\n\nCollections that contain this guide\n-----------------------------------\n\nThis guide is part of these curated Quick Guide collections that cover\nbroader Android development goals: \n\n### Display a list or grid\n\nLists and grids allow your app to display collections in a visually pleasing form that's easy for users to consume. \n[Quick guide collection](/develop/ui/compose/quick-guides/collections/display-a-list-or-grid) \n\n### Display interactive components\n\nLearn how composable functions can enable you to easily create beautiful UI components based on the Material Design design system. \n[Quick guide collection](/develop/ui/compose/quick-guides/collections/display-interactive-components) \n\n### Compose basics (video collection)\n\nThis series of videos introduces various Compose APIs, quickly showing you what's available and how to use them. \n[Quick guide collection](/develop/ui/compose/quick-guides/collections/compose-basics) \n\nHave questions or feedback\n--------------------------\n\nGo to our frequently asked questions page and learn about quick guides or reach out and let us know your thoughts. \n[Go to FAQ](/quick-guides/faq) [Leave feedback](https://issuetracker.google.com/issues/new?component=1573691&template=1993320)"]]