Jetpack Compose Academy · Lección

Arrastre, deslizamiento y lanzamiento

Siga el movimiento y el impulso.

Lección 2 de 413 pasos

Arrastre, deslizamiento y lanzamiento 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.

Following the Finger

Dragging means tracking how far a finger moves and updating the UI to match. Compose makes this smooth with dedicated drag detectors. ✋

Detect Drag Gestures

Inside pointerInput, call detectDragGestures. Its onDrag lambda fires repeatedly with the change and the distance moved since the last event.

detectDragGestures { change, drag -> /* move */ }

Accumulate the Offset

Keep a state Offset and add each drag delta to it. Then feed that offset into a Modifier so the element follows your finger.

var offset by remember { mutableStateOf(Offset.Zero) }
offset += drag

Apply with offset Modifier

Use the offset modifier to move a composable by your tracked pixels. Convert with roundToInt so it positions cleanly on screen.

Modifier.offset { IntOffset(offset.x.roundToInt(), offset.y.roundToInt()) }

Consume the Change

Call change.consume() in your drag handler. This tells parents you handled the event so they do not also react to it.

detectDragGestures { change, drag -> change.consume() }

Limit to One Axis

Need only sideways motion? Use detectHorizontalDragGestures, or detectVerticalDragGestures for up and down. They report a single Float delta.

detectHorizontalDragGestures { _, dx -> x += dx }

Swipe to Dismiss

A swipe is just a drag you judge at the end. If the finger traveled far enough, treat it as a dismiss instead of snapping back.

The High-Level draggable

For simple single-axis dragging, the draggable modifier is easier. Pair it with rememberDraggableState to collect the delta.

Modifier.draggable(state, orientation = Orientation.Horizontal)

Fling Needs Velocity

A fling keeps moving after release based on speed. Track velocity with a VelocityTracker as the finger moves to capture that momentum.

val tracker = VelocityTracker()

Animate the Decay

Feed the release velocity into an Animatable with a decay spec. It glides to a natural stop, mimicking real physics. 🌀

animatable.animateDecay(velocity, exponentialDecay())

Know When It Ends

detectDragGestures also gives you onDragEnd and onDragCancel. Use them to snap back, settle, or kick off your fling animation.

detectDragGestures(onDragEnd = { /* fling here */ }) {...}

Quick Check

What does a fling animation need that a plain drag does not?

Recap: Move with Momentum

You tracked drags with detectDragGestures, accumulated an offset, judged swipes, and used velocity for a fling. Touch now feels alive. 🎉

Gratis para empezar

Aprende Kotlin con un tutor de IA — gratis

Escribe y ejecuta código real en tu navegador, obtén ayuda instantánea de un tutor de IA disponible 24/7 y continúa donde lo dejaste en la web o en la aplicación.

Cursos
30
Lecciones
120

Preguntas frecuentes

¿La lección «Arrastre, deslizamiento y lanzamiento» es gratis?

Sí — el texto completo de «Arrastre, deslizamiento y lanzamiento» 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 «Arrastre, deslizamiento y lanzamiento»?

Siga el movimiento y el impulso. 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 «Arrastre, deslizamiento y lanzamiento»?

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. pointerInput y detectTapGestures
  2. Arrastre, deslizamiento y lanzamiento
  3. Transform: desplazar, ampliar y girar
  4. Conexiones de desplazamiento anidado
← Volver a Jetpack Compose Academy