Для навигации с помощью Compose для Wear OS требуются те же три компонента, что и для приложений, отличных от Wear OS: контроллер навигации, хост и график.
Котлин
val navController = rememberSwipeDismissableNavController()
NavController
— это основной API, используемый для навигации в приложениях Compose. Он управляет навигацией между компонуемыми элементами в хосте навигации, который в Wear OS — SwipeDismissableNavHost
.
Котлин
val navController = rememberSwipeDismissableNavController()
SwipeDismissableNavHost(
navController = navController,
startDestination = "message_list"
) {
// TODO: build navigation graph
}
Как и компонуемый объект NavHost
, он принимает ссылку на навигационный контроллер, маршрут для начальной точки назначения и построитель для навигационного графика, который здесь показан как конечная лямбда.
Начальный пункт назначения должен быть указан в конструкторе навигационного графика, а также все остальные пункты назначения, по которым должна быть доступна навигация с помощью навигационного контроллера.
В приложении Wear OS объявите
SwipeDismissableNavHost
как содержимое
AppScaffold
для поддержки компонентов верхнего уровня, таких как время, индикатор прокрутки/позиции и индикатор страницы. Используйте объект
AppScaffold
над
SwipeDismissableNavHost
и
ScreenScaffold
на уровне экрана, чтобы добавить объект
TimeText
на экран по умолчанию и убедиться, что он правильно анимируется при навигации между экранами. Кроме того,
ScreenScaffold
добавляет
PositionIndicator
для прокручиваемого содержимого.
AppScaffold {
val navController = rememberSwipeDismissableNavController()
SwipeDismissableNavHost(
navController = navController,
startDestination = "message_list"
) {
composable("message_list") {
MessageList(onMessageClick = { id ->
navController.navigate("message_detail/$id")
})
}
composable("message_detail/{id}") {
MessageDetail(id = it.arguments?.getString("id")!!)
}
}
}
}
// Implementation of one of the screens in the navigation
@Composable
fun MessageDetail(id: String) {
// .. Screen level content goes here
val scrollState = rememberTransformingLazyColumnState()
val padding = rememberResponsiveColumnPadding(
first = ColumnItemType.BodyText
)
ScreenScaffold(
scrollState = scrollState,
contentPadding = padding
) {
// Screen content goes here
Чтобы узнать больше о Jetpack Navigation, ознакомьтесь с разделом Навигация с помощью Compose или пройдите лабораторную работу по коду Jetpack Compose Navigation .
{% дословно %}
{% endverbatim %} Рекомендовано для вас
{% дословно %} {% endverbatim %}
Контент и образцы кода на этой странице предоставлены по лицензиям. Java и OpenJDK – это зарегистрированные товарные знаки корпорации Oracle и ее аффилированных лиц.
Последнее обновление: 2025-08-28 UTC.
[null,null,["Последнее обновление: 2025-08-28 UTC."],[],[],null,["Compose for Wear OS Material version 2.5 3\n\n*** ** * ** ***\n\nThe [Navigation component](/guide/navigation) in Android Jetpack provides\nsupport for Jetpack Compose applications. You can navigate between composables\nwhile taking advantage of the Navigation component's infrastructure and\nfeatures.\n\nThis page describes the differences with Jetpack Navigation on Compose for Wear\nOS.\n| **Note:** If you are not familiar with the Navigation component, review the [Navigating with Compose](/jetpack/compose/navigation) resources before continuing.\n\nSetup\n\nUse the following dependency in your app module's build.gradle file: \n\nKotlin \n\n```kotlin\ndependencies {\n def wear_compose_version = \"1.5.0\"\n implementation \"androidx.wear.compose:compose-navigation:$wear_compose_version\"\n}\n```\n\nThis is used **instead** of the `androidx.navigation:navigation-compose`\nartifact because it provides alternative implementations specific to Wear OS.\n\nCreate a navigation controller, host and graph\n\nNavigating with Compose for Wear OS requires the same three components needed on\nnon-Wear OS apps: the navigation controller, host and graph.\n\nUse\n[`rememberSwipeDismissableNavController()`](/reference/kotlin/androidx/wear/compose/navigation/package-summary#rememberSwipeDismissableNavController())\nto create an instance of `WearNavigator`, an implementation of `NavController`\nsuitable for Wear OS applications: \n\nKotlin \n\n```kotlin\nval navController = rememberSwipeDismissableNavController()\n```\n\nThe [`NavController`](/reference/kotlin/androidx/navigation/NavController) is\nthe primary API used to navigate in Compose applications. It controls navigating\nbetween composables in the navigation host which, on Wear OS, is\n[`SwipeDismissableNavHost`](/reference/kotlin/androidx/wear/compose/navigation/package-summary#SwipeDismissableNavHost(androidx.navigation.NavHostController,kotlin.String,androidx.compose.ui.Modifier,androidx.wear.compose.navigation.SwipeDismissableNavHostState,kotlin.String,kotlin.Function1)). \n\nKotlin \n\n```kotlin\nval navController = rememberSwipeDismissableNavController()\nSwipeDismissableNavHost(\n navController = navController,\n startDestination = \"message_list\"\n) {\n // TODO: build navigation graph\n}\n```\n\nLike the\n[`NavHost` composable](/reference/kotlin/androidx/navigation/compose/package-summary#NavHost(androidx.navigation.NavHostController,kotlin.String,androidx.compose.ui.Modifier,kotlin.String,kotlin.Function1)),\nit takes a reference to the navigation controller, the route for the start\ndestination, and the builder for the navigation graph which is shown here as a\ntrailing lambda.\n\nThe start destination must be provided in the navigation graph builder, along\nwith all other destinations that should be navigable with the navigation\ncontroller.\nIn your Wear OS app, declare [`SwipeDismissableNavHost`](/reference/kotlin/androidx/wear/compose/navigation/package-summary#SwipeDismissableNavHost(androidx.navigation.NavHostController,androidx.navigation.NavGraph,androidx.compose.ui.Modifier,kotlin.Boolean,androidx.wear.compose.navigation.SwipeDismissableNavHostState)) as a content of the [`AppScaffold`](/reference/kotlin/androidx/wear/compose/material3/package-summary#AppScaffold(androidx.compose.ui.Modifier,kotlin.Function0,kotlin.Function1)) to support top-level components like time, scroll/position indicator, and page indicator. Use a [`AppScaffold`](/reference/kotlin/androidx/wear/compose/material3/package-summary#AppScaffold(androidx.compose.ui.Modifier,kotlin.Function0,kotlin.Function1)) object above the [`SwipeDismissableNavHost`](/reference/kotlin/androidx/wear/compose/navigation/package-summary#SwipeDismissableNavHost(androidx.navigation.NavHostController,androidx.navigation.NavGraph,androidx.compose.ui.Modifier,kotlin.Boolean,androidx.wear.compose.navigation.SwipeDismissableNavHostState)) and the [`ScreenScaffold`](/reference/kotlin/androidx/wear/compose/material3/package-summary#ScreenScaffold(androidx.wear.compose.foundation.lazy.ScalingLazyListState,kotlin.Function1,androidx.compose.ui.Modifier,androidx.compose.foundation.layout.PaddingValues,kotlin.Function0,kotlin.Function1,androidx.compose.ui.unit.Dp,kotlin.Function2)) at the screen level to add a `TimeText` object to the screen by default and to make sure it animates correctly when navigating between screens. Additionally, `ScreenScaffold` adds a `PositionIndicator` for scrollable content. \n\n```kotlin\n AppScaffold {\n val navController = rememberSwipeDismissableNavController()\n SwipeDismissableNavHost(\n navController = navController,\n startDestination = \"message_list\"\n ) {\n composable(\"message_list\") {\n MessageList(onMessageClick = { id -\u003e\n navController.navigate(\"message_detail/$id\")\n })\n }\n composable(\"message_detail/{id}\") {\n MessageDetail(id = it.arguments?.getString(\"id\")!!)\n }\n }\n }\n}\n\n// Implementation of one of the screens in the navigation\n@Composable\nfun MessageDetail(id: String) {\n // .. Screen level content goes here\n val scrollState = rememberTransformingLazyColumnState()\n\n val padding = rememberResponsiveColumnPadding(\n first = ColumnItemType.BodyText\n )\n\n ScreenScaffold(\n scrollState = scrollState,\n contentPadding = padding\n ) {\n // Screen content goes here \nhttps://github.com/android/snippets/blob/dd30aee903e8c247786c064faab1a9ca8d10b46e/wear/src/main/java/com/example/wear/snippets/m3/navigation/Navigation.kt#L44-L76\n```\n\nTo learn more about Jetpack Navigation, see\n[Navigating with Compose](/jetpack/compose/navigation) or take the\n[Jetpack Compose Navigation code lab](/codelabs/jetpack-compose-navigation).\n\nRecommended for you\n\n- Note: link text is displayed when JavaScript is off\n- [Migrate Jetpack Navigation to Navigation Compose](/develop/ui/compose/migrate/migration-scenarios/navigation)\n- [Navigation with Compose](/develop/ui/compose/navigation)\n- [Navigate between screens with Compose](/codelabs/basic-android-kotlin-compose-navigation)"]]