Оптимизируйте свои подборки
Сохраняйте и классифицируйте контент в соответствии со своими настройками.
Вкладки позволяют группировать связанный контент. Существует два типа вкладок:
Основные вкладки : располагаются в верхней части панели контента под верхней панелью приложений. Они отображают основные назначения контента и должны использоваться, когда требуется только один набор вкладок.
Вторичные вкладки : используются в области контента для дальнейшего разделения связанного контента и создания иерархии. Они необходимы, когда на экране требуется более одного уровня вкладок.
Рисунок 1. Первичные вкладки (1) и вторичные вкладки (2).
На этой странице показано, как отображать основные вкладки в вашем приложении со связанными экранами и базовой навигацией.
API поверхность
Для реализации вкладок используйте компонуемые объекты Tab , PrimaryTabRow и SecondaryTabRow . Компонуемый объект Tab представляет собой отдельную вкладку в строке и обычно используется внутри объекта PrimaryTabRow (для вкладок первичных индикаторов) или SecondaryTabRow (для вкладок вторичных индикаторов).
Tab включает в себя следующие ключевые параметры:
selected : определяет, будет ли текущая вкладка визуально выделена.
onClick() : обязательная лямбда-функция, определяющая действие, выполняемое при щелчке пользователя по вкладке. Здесь обычно обрабатываются события навигации, обновляется состояние выбранной вкладки или загружается соответствующий контент.
text : отображает текст на вкладке. Необязательно.
icon : отображает значок на вкладке. Необязательно.
enabled : контролирует, включена ли вкладка и можно ли с ней взаимодействовать. Если установлено значение false, вкладка отображается в отключенном состоянии и не реагирует на нажатия.
Пример: навигация с помощью вкладок
Следующий фрагмент реализует верхнюю панель навигации с вкладками для навигации между различными экранами в приложении:
Контент и образцы кода на этой странице предоставлены по лицензиям. Java и OpenJDK – это зарегистрированные товарные знаки корпорации Oracle и ее аффилированных лиц.
Последнее обновление: 2025-08-27 UTC.
[null,null,["Последнее обновление: 2025-08-27 UTC."],[],[],null,["Tabs allow you to organize groups of related content. There are two types of\ntabs:\n\n- **Primary tabs**: Placed at the top of the content pane under a top app bar. They display the main content destinations, and should be used when just one set of tabs are needed.\n- **Secondary tabs**: Used within a content area to further separate related content and establish hierarchy. They are necessary when a screen requires more than one level of tabs.\n\n**Figure 1.** Primary tabs (1) and secondary tabs (2).\n\nThis page shows how to display primary tabs in your app with related screens and\nbasic navigation.\n\nAPI surface\n\nUse the [`Tab`](/reference/kotlin/androidx/compose/material3/package-summary#Tab(kotlin.Boolean,kotlin.Function0,androidx.compose.ui.Modifier,kotlin.Boolean,kotlin.Function0,kotlin.Function0,androidx.compose.ui.graphics.Color,androidx.compose.ui.graphics.Color,androidx.compose.foundation.interaction.MutableInteractionSource)), [`PrimaryTabRow`](/reference/kotlin/androidx/compose/material3/package-summary#PrimaryTabRow(kotlin.Int,androidx.compose.ui.Modifier,androidx.compose.ui.graphics.Color,androidx.compose.ui.graphics.Color,kotlin.Function1,kotlin.Function0,kotlin.Function0)), and [`SecondaryTabRow`](/reference/kotlin/androidx/compose/material3/package-summary#SecondaryTabRow(kotlin.Int,androidx.compose.ui.Modifier,androidx.compose.ui.graphics.Color,androidx.compose.ui.graphics.Color,kotlin.Function1,kotlin.Function0,kotlin.Function0)) composables\nto implement tabs. The `Tab` composable represents an individual tab within the\nrow, and is typically used inside of a `PrimaryTabRow` (for primary indicator\ntabs) or `SecondaryTabRow` (for secondary indicator tabs).\n\n`Tab` includes the following key parameters:\n\n- `selected`: Determines whether the current tab is visually highlighted.\n- `onClick()`: A required lambda function that defines the action to be performed when the user clicks on the tab. This is where you typically handle navigation events, update the selected tab state, or load corresponding content.\n- `text`: Displays text within the tab. Optional.\n- `icon`: Displays an icon within the tab. Optional.\n- `enabled`: Controls whether the tab is enabled and can be interacted with. If set to false, the tab appears in a disabled state and won't respond to clicks.\n\nExample: Tab-based navigation\n\nThe following snippet implements a top navigation bar with tabs to navigate\nbetween different screens in an app:\n| **Note:** The [full source code](https://github.com/android/snippets/blob/main/compose/snippets/src/main/java/com/example/compose/snippets/components/Navigation.kt) includes the code that establishes the basic navigation structure for the following example.\n\n\n```kotlin\n@Composable\nfun NavigationTabExample(modifier: Modifier = Modifier) {\n val navController = rememberNavController()\n val startDestination = Destination.SONGS\n var selectedDestination by rememberSaveable { mutableIntStateOf(startDestination.ordinal) }\n\n Scaffold(modifier = modifier) { contentPadding -\u003e\n PrimaryTabRow(selectedTabIndex = selectedDestination, modifier = Modifier.padding(contentPadding)) {\n Destination.entries.forEachIndexed { index, destination -\u003e\n Tab(\n selected = selectedDestination == index,\n onClick = {\n navController.navigate(route = destination.route)\n selectedDestination = index\n },\n text = {\n Text(\n text = destination.label,\n maxLines = 2,\n overflow = TextOverflow.Ellipsis\n )\n }\n )\n }\n }\n AppNavHost(navController, startDestination)\n }\n}https://github.com/android/snippets/blob/5673ffc60b614daf028ee936227128eb8c4f9781/compose/snippets/src/main/java/com/example/compose/snippets/components/Navigation.kt#L186-L213\n```\n\n\u003cbr /\u003e\n\nKey points\n\n- `PrimaryTabRow` displays a horizontal row of tabs, with each tab corresponding to a `Destination`.\n- `val navController = rememberNavController()` creates and remembers an instance of [`NavHostController`](/reference/androidx/navigation/NavHostController), which manages the navigation within a [`NavHost`](/reference/androidx/navigation/NavHost).\n- `var selectedDestination by rememberSaveable {\n mutableIntStateOf(startDestination.ordinal) }` manages the state of the selected tab.\n - `startDestination.ordinal` gets the numerical index (position) of the `Destination.SONGS` enum entry.\n- When you click a tab, the `onClick` lambda calls `navController.navigate(route = destination.route)` to navigate to the corresponding screen.\n- The `onClick` lambda of the `Tab` updates the `selectedDestination` state to visually highlight the clicked tab.\n- It calls the `AppNavHost` composable, passing the `navController` and `startDestination`, to display the actual content of the selected screen.\n\nResult\n\nThe following image shows the result of the previous snippet:\n**Figure 2.** 3 tabs--- Songs, Album, and Playlist--- arranged horizontally.\n\nAdditional resources\n\n- [Material 3 - Tabs](https://m3.material.io/components/tabs/guidelines)\n- [Navigation with Compose](/develop/ui/compose/navigation)"]]