0Pricing
Jetpack Compose Academy · Lección

Resaltar la ruta seleccionada

Sincronice la selección con la pila de navegación.

Resaltar la ruta seleccionada es una lección gratuita de Jetpack Compose Academy en CoddyKit. Esta es la lección 2 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Jetpack Compose Academy, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Jetpack Compose Academy incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

Selection Must Be Real

A tab should light up because of where the user actually is, not a value you set by hand. The back stack is your source of truth. 🧭

Read the Current Entry

Ask the NavController for the live currentBackStackEntryAsState. It updates automatically every time navigation changes.

val entry by navController.currentBackStackEntryAsState()

Get the Active Route

From that entry you read the active route string off its destination. That string tells you which tab is showing.

val route = entry?.destination?.route

Compare to Mark Selected

Now set each item selected by comparing the active route to that tab route. The match becomes the highlighted selected tab.

selected = route == tab.route

Hierarchy Beats Equality

For nested graphs, exact equality can miss. Checking the destination hierarchy marks a tab active even on its sub-screens.

selected = entry?.destination?.hierarchy?.any {
  it.route == tab.route
} == true

Navigate on Tap

In onClick, call navController.navigate with the tab route to move there. The selection then follows the back stack on its own.

onClick = { navController.navigate(tab.route) }

Avoid Stacking Copies

Tapping a tab repeatedly should not pile up screens. Use launchSingleTop so only one copy of a destination stays on top.

navController.navigate(tab.route) {
  launchSingleTop = true
}

Pop to the Start

Pressing back from any tab should return to your home tab, not walk every tab you visited. popUpTo the start destination fixes that.

popUpTo(navController.graph.startDestinationId) {
  saveState = true
}

Tint the Active Tab

NavigationBarItem auto-tints the selected item, but you can theme it with colors so the active tab matches your brand.

colors = NavigationBarItemDefaults.colors(
  selectedIconColor = MaterialTheme.colorScheme.primary
)

Label Visibility

Use alwaysShowLabel to decide if unselected tabs still show text. Showing only the active label is a common clean look.

alwaysShowLabel = false

One Reactive Loop

Put it together: read the route once, then in your forEach compare each tab to it. Selection now mirrors navigation perfectly.

Quick Check

You wired selection to the back stack. One quick question.

Recap

You synced highlighting to the back stack: read the current route, compare per tab, navigate with launchSingleTop and popUpTo. Selection now stays honest. 🎯

Preguntas frecuentes

¿La lección «Resaltar la ruta seleccionada» es gratis?

Sí — el texto completo de «Resaltar la ruta seleccionada» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Jetpack Compose Academy, actualiza a CoddyKit PRO. El curso de Jetpack Compose Academy incluye 4 lecciones en total.

¿Qué aprenderé en «Resaltar la ruta seleccionada»?

Sincronice la selección con la pila de navegación. Practicas Jetpack Compose Academy con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar Jetpack Compose Academy?

No se requiere experiencia previa. Jetpack Compose Academy en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 2 de 4.

¿Cuánto tiempo toma la lección «Resaltar la ruta seleccionada»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de Jetpack Compose Academy?

Sí. Cada lección de Jetpack Compose Academy incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. NavigationBar con varias pestañas
  2. Resaltar la ruta seleccionada
  3. Conservar el estado de las pestañas al cambiar
  4. TabRow y páginas deslizables
← Volver a Jetpack Compose Academy