고급 애니메이션의 예: 동작
컬렉션을 사용해 정리하기
내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요.
터치 이벤트와 애니메이션을 사용할 때는 애니메이션만 사용할 때에 비해 여러 가지 사항을 고려해야 합니다. 무엇보다도 사용자 상호작용의 우선순위가 가장 높아야 하므로 터치 이벤트가 시작될 때 진행 중인 애니메이션을 중단해야 할 수도 있습니다.
아래 예에서는 Animatable
을 사용하여 원 구성요소의 오프셋 위치를 나타냅니다. 터치 이벤트는 pointerInput
수정자로 처리됩니다. 새 탭 이벤트가 감지되면 animateTo
를 호출하여 오프셋 값을 탭 위치에 애니메이션 처리합니다. 애니메이션 도중에도 탭 이벤트가 발생할 수 있으며 이 경우 animateTo
는 진행 중인 애니메이션을 중단하고 중단된 애니메이션의 속도를 유지하면서 새 타겟 위치로 애니메이션을 시작합니다.
@Composable
fun Gesture() {
val offset = remember { Animatable(Offset(0f, 0f), Offset.VectorConverter) }
Box(
modifier = Modifier
.fillMaxSize()
.pointerInput(Unit) {
coroutineScope {
while (true) {
// Detect a tap event and obtain its position.
awaitPointerEventScope {
val position = awaitFirstDown().position
launch {
// Animate to the tap position.
offset.animateTo(position)
}
}
}
}
}
) {
Circle(modifier = Modifier.offset { offset.value.toIntOffset() })
}
}
private fun Offset.toIntOffset() = IntOffset(x.roundToInt(), y.roundToInt())
또 하나의 빈번한 패턴은 애니메이션 값을 드래그와 같은 터치 이벤트에서 발생하는 값과 동기화해야 한다는 것입니다. 아래 예에서는 '스와이프하여 닫기'가 SwipeToDismiss
컴포저블을 사용하는 대신 Modifier
로 구현됩니다. 요소의 가로 오프셋은 Animatable
로 표시됩니다. 이 API에는 동작 애니메이션에 유용한 특성이 있습니다. 특성의 값은 애니메이션은 물론 터치 이벤트에서도 변경할 수 있습니다. 터치 다운 이벤트가 수신되면 Animatable
이 stop
메서드를 사용하여 정지되고 진행 중인 애니메이션이 중단됩니다.
드래그 이벤트 중에 snapTo
를 사용하여 Animatable
값을 터치 이벤트에서 계산된 값으로 업데이트합니다. 플링의 경우 Compose는 드래그 이벤트를 기록하고 속도를 계산할 수 있도록 VelocityTracker
를 제공합니다. 플링 애니메이션의 경우 animateDecay
에 직접 속도를 제공할 수 있습니다. 오프셋 값을 원래 위치로 되돌리려는 경우 animateTo
메서드를 사용하여 0f
의 타겟 오프셋 값을 지정합니다.
fun Modifier.swipeToDismiss(
onDismissed: () -> Unit
): Modifier = composed {
val offsetX = remember { Animatable(0f) }
pointerInput(Unit) {
// Used to calculate fling decay.
val decay = splineBasedDecay<Float>(this)
// Use suspend functions for touch events and the Animatable.
coroutineScope {
while (true) {
val velocityTracker = VelocityTracker()
// Stop any ongoing animation.
offsetX.stop()
awaitPointerEventScope {
// Detect a touch down event.
val pointerId = awaitFirstDown().id
horizontalDrag(pointerId) { change ->
// Update the animation value with touch events.
launch {
offsetX.snapTo(
offsetX.value + change.positionChange().x
)
}
velocityTracker.addPosition(
change.uptimeMillis,
change.position
)
}
}
// No longer receiving touch events. Prepare the animation.
val velocity = velocityTracker.calculateVelocity().x
val targetOffsetX = decay.calculateTargetValue(
offsetX.value,
velocity
)
// The animation stops when it reaches the bounds.
offsetX.updateBounds(
lowerBound = -size.width.toFloat(),
upperBound = size.width.toFloat()
)
launch {
if (targetOffsetX.absoluteValue <= size.width) {
// Not enough velocity; Slide back.
offsetX.animateTo(
targetValue = 0f,
initialVelocity = velocity
)
} else {
// The element was swiped away.
offsetX.animateDecay(velocity, decay)
onDismissed()
}
}
}
}
}
.offset { IntOffset(offsetX.value.roundToInt(), 0) }
}
추천 서비스
이 페이지에 나와 있는 콘텐츠와 코드 샘플에는 콘텐츠 라이선스에서 설명하는 라이선스가 적용됩니다. 자바 및 OpenJDK는 Oracle 및 Oracle 계열사의 상표 또는 등록 상표입니다.
최종 업데이트: 2025-08-24(UTC)
[[["이해하기 쉬움","easyToUnderstand","thumb-up"],["문제가 해결됨","solvedMyProblem","thumb-up"],["기타","otherUp","thumb-up"]],[["필요한 정보가 없음","missingTheInformationINeed","thumb-down"],["너무 복잡함/단계 수가 너무 많음","tooComplicatedTooManySteps","thumb-down"],["오래됨","outOfDate","thumb-down"],["번역 문제","translationIssue","thumb-down"],["샘플/코드 문제","samplesCodeIssue","thumb-down"],["기타","otherDown","thumb-down"]],["최종 업데이트: 2025-08-24(UTC)"],[],[],null,["# Advanced animation example: Gestures\n\nThere are several things we have to take into consideration when we are working\nwith touch events and animations, compared to when we are working with\nanimations alone. First of all, we might need to interrupt an ongoing animation\nwhen touch events begin as user interaction should have the highest priority.\n\nIn the example below, we use an `Animatable` to represent the offset position of\na circle component. Touch events are processed with the\n[`pointerInput`](/reference/kotlin/androidx/compose/ui/input/pointer/package-summary#(androidx.compose.ui.Modifier).pointerInput(kotlin.Any,%20kotlin.coroutines.SuspendFunction1))\nmodifier. When we detect a new tap event, we call `animateTo` to animate the\noffset value to the tap position. A tap event can happen during the animation\ntoo, and in that case, `animateTo` interrupts the ongoing animation and starts\nthe animation to the new target position while maintaining the velocity of the\ninterrupted animation.\n\n\n```kotlin\n@Composable\nfun Gesture() {\n val offset = remember { Animatable(Offset(0f, 0f), Offset.VectorConverter) }\n Box(\n modifier = Modifier\n .fillMaxSize()\n .pointerInput(Unit) {\n coroutineScope {\n while (true) {\n // Detect a tap event and obtain its position.\n awaitPointerEventScope {\n val position = awaitFirstDown().position\n\n launch {\n // Animate to the tap position.\n offset.animateTo(position)\n }\n }\n }\n }\n }\n ) {\n Circle(modifier = Modifier.offset { offset.value.toIntOffset() })\n }\n}\n\nprivate fun Offset.toIntOffset() = IntOffset(x.roundToInt(), y.roundToInt())https://github.com/android/snippets/blob/dd30aee903e8c247786c064faab1a9ca8d10b46e/compose/snippets/src/main/java/com/example/compose/snippets/animations/AdvancedAnimationSnippets.kt#L62-L88\n```\n\n\u003cbr /\u003e\n\nAnother frequent pattern is we need to synchronize animation values with values\ncoming from touch events, such as drag. In the example below, we see \"swipe to\ndismiss\" implemented as a `Modifier` (rather than using the\n[`SwipeToDismiss`](/reference/kotlin/androidx/compose/material/package-summary#SwipeToDismiss(androidx.compose.material.DismissState,%20androidx.compose.ui.Modifier,%20kotlin.collections.Set,%20kotlin.Function1,%20kotlin.Function1,%20kotlin.Function1))\ncomposable). The horizontal offset of the element is represented as an\n`Animatable`. This API has a characteristic useful in gesture animation. Its\nvalue can be changed by touch events as well as the animation. When we receive a\ntouch down event, we stop the `Animatable` by the `stop` method so that any\nongoing animation is intercepted.\n\nDuring a drag event, we use `snapTo` to update the `Animatable` value with the\nvalue calculated from touch events. For fling, Compose provides\n`VelocityTracker` to record drag events and calculate velocity. The velocity can\nbe fed directly to `animateDecay` for the fling animation. When we want to slide\nthe offset value back to the original position, we specify the target offset\nvalue of `0f` with the `animateTo` method.\n\n\n```kotlin\nfun Modifier.swipeToDismiss(\n onDismissed: () -\u003e Unit\n): Modifier = composed {\n val offsetX = remember { Animatable(0f) }\n pointerInput(Unit) {\n // Used to calculate fling decay.\n val decay = splineBasedDecay\u003cFloat\u003e(this)\n // Use suspend functions for touch events and the Animatable.\n coroutineScope {\n while (true) {\n val velocityTracker = VelocityTracker()\n // Stop any ongoing animation.\n offsetX.stop()\n awaitPointerEventScope {\n // Detect a touch down event.\n val pointerId = awaitFirstDown().id\n\n horizontalDrag(pointerId) { change -\u003e\n // Update the animation value with touch events.\n launch {\n offsetX.snapTo(\n offsetX.value + change.positionChange().x\n )\n }\n velocityTracker.addPosition(\n change.uptimeMillis,\n change.position\n )\n }\n }\n // No longer receiving touch events. Prepare the animation.\n val velocity = velocityTracker.calculateVelocity().x\n val targetOffsetX = decay.calculateTargetValue(\n offsetX.value,\n velocity\n )\n // The animation stops when it reaches the bounds.\n offsetX.updateBounds(\n lowerBound = -size.width.toFloat(),\n upperBound = size.width.toFloat()\n )\n launch {\n if (targetOffsetX.absoluteValue \u003c= size.width) {\n // Not enough velocity; Slide back.\n offsetX.animateTo(\n targetValue = 0f,\n initialVelocity = velocity\n )\n } else {\n // The element was swiped away.\n offsetX.animateDecay(velocity, decay)\n onDismissed()\n }\n }\n }\n }\n }\n .offset { IntOffset(offsetX.value.roundToInt(), 0) }\n}https://github.com/android/snippets/blob/dd30aee903e8c247786c064faab1a9ca8d10b46e/compose/snippets/src/main/java/com/example/compose/snippets/animations/AdvancedAnimationSnippets.kt#L94-L152\n```\n\n\u003cbr /\u003e\n\nRecommended for you\n-------------------\n\n- Note: link text is displayed when JavaScript is off\n- [Value-based animations](/develop/ui/compose/animation/value-based)\n- [Drag, swipe, and fling](/develop/ui/compose/touch-input/pointer-input/drag-swipe-fling)\n- [Understand gestures](/develop/ui/compose/touch-input/pointer-input/understand-gestures)"]]