Анимации на основе жестов
Управляйте движением с помощью перетаскивания и смахивания.
«Анимации на основе жестов» — бесплатный урок Jetpack Compose Academy на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Jetpack Compose Academy, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Jetpack Compose Academy содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
Motion You Control by Touch
State-driven animations run on their own, but some motion should follow your finger. Gesture-driven animations let drags and swipes steer the movement. ✨
Track the Offset
Hold the current position in state. The most direct tool is the Animatable, which stores a value and can both jump and animate to it.
val offsetX = remember { Animatable(0f) }Read Drag Events
Use pointerInput with detectDragGestures to receive each drag delta as the user moves their finger across the element.
Modifier.pointerInput(Unit) { detectDragGestures { _, drag -> } }Follow the Finger
During a drag, call snapTo to move instantly to the new position. Snapping keeps the element glued to the finger with no lag.
scope.launch { offsetX.snapTo(offsetX.value + drag.x) }Apply the Offset
Feed the value into an offset modifier so the Composable physically moves. The view tracks every pixel of the drag in real time.
Modifier.offset { IntOffset(offsetX.value.roundToInt(), 0) }Animate on Release
When the finger lifts, switch from snap to animateTo so the element glides back home or to the nearest anchor smoothly.
scope.launch { offsetX.animateTo(0f) }Carry the Momentum
Capture fling velocity from onDragEnd and pass it to animateDecay. The element keeps coasting after release, just like real flicks. 🌀
offsetX.animateDecay(velocity, exponentialDecay())Swipe Between Anchors
For swipe-to-dismiss or sliders, snap to fixed stops. anchoredDraggable ties gestures to defined anchor points and settles between them.
Coroutines Drive It
Animatable updates are suspend functions, so launch them in a coroutine scope. Grab one with rememberCoroutineScope inside your Composable.
val scope = rememberCoroutineScope()Interruptible by Design
Because gestures and animations share the same Animatable, a new touch interrupts any running animation, handing control straight back to the user.
The Feel of Native Apps
Combining snap during drag with decay and spring on release is the secret to fluid, natural gestures that feel responsive and alive.
Quick Check
While the finger is dragging, which Animatable call keeps the element glued to the touch?
Recap: Touch Meets Motion
You combined pointerInput with Animatable: snapTo while dragging, then animateTo or animateDecay on release for fluid, gesture-driven motion. 🎉
Часто задаваемые вопросы
Урок «Анимации на основе жестов» бесплатный?
Да — полный текст урока «Анимации на основе жестов» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Jetpack Compose Academy, подпишись на CoddyKit PRO. Курс Jetpack Compose Academy содержит 4 уроков всего.
Чему я научусь в уроке «Анимации на основе жестов»?
Управляйте движением с помощью перетаскивания и смахивания. Ты практикуешь Jetpack Compose Academy с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Jetpack Compose Academy?
Предыдущий опыт не требуется. Jetpack Compose Academy на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.
Сколько времени занимает урок «Анимации на основе жестов»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Jetpack Compose Academy?
Да. Каждый урок Jetpack Compose Academy включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- animate*AsState для простых интерполяций
- AnimatedVisibility и Crossfade
- updateTransition для согласованного движения
- Анимации на основе жестов