Arrastar, Deslizar e Arremessar
Acompanhe o movimento e o impulso.
Arrastar, Deslizar e Arremessar é uma aula grátis de Jetpack Compose Academy no CoddyKit. Esta é a aula 2 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Jetpack Compose Academy, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Jetpack Compose Academy inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em 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 += dragApply 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. 🎉
Perguntas Frequentes
A aula “Arrastar, Deslizar e Arremessar” é grátis?
Sim — o texto completo de “Arrastar, Deslizar e Arremessar” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Jetpack Compose Academy, atualize para CoddyKit PRO. O curso de Jetpack Compose Academy inclui 4 aulas no total.
O que vou aprender em “Arrastar, Deslizar e Arremessar”?
Acompanhe o movimento e o impulso. Você pratica Jetpack Compose Academy com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Jetpack Compose Academy?
Nenhuma experiência prévia é necessária. Jetpack Compose Academy no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 2 de 4.
Quanto tempo leva a aula “Arrastar, Deslizar e Arremessar”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Jetpack Compose Academy?
Sim. Cada aula de Jetpack Compose Academy inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- pointerInput e detectTapGestures
- Arrastar, Deslizar e Arremessar
- Transformar: Deslocar, Ampliar e Girar
- Conexões de Rolagem Aninhada