我有 Row 带有 .horizontalScroll(),我需要弹跳动画效果。也就是说,当列表出现时,它会向前滚动一点,然后返回。同时,我需要在返回滚动时使用弹簧效果。这是我的实现:
val scrollState = rememberScrollState()
val coroutineScope = rememberCoroutineScope()
val bounceDistance = 150
LaunchedEffect(Unit) {
val animatable = Animatable(scrollState.value.toFloat())
coroutineScope.launch {
animatable.animateTo(
targetValue = bounceDistance.toFloat(),
animationSpec = tween(
durationMillis = 200,
easing = LinearOutSlowInEasing
)
)
scrollState.scrollTo(animatable.value.toInt())
animatable.animateTo(
targetValue = 0f,
animationSpec = spring(
dampingRatio = 0.4f,
stiffness = Spring.StiffnessLow
)
)
scrollState.scrollTo(animatable.value.toInt())
animatable.animateTo(
targetValue = bounceDistance * 0.3f,
animationSpec = tween(
durationMillis = 400,
easing = LinearOutSlowInEasing
)
)
scrollState.scrollTo(animatable.value.toInt())
animatable.animateTo(
targetValue = 0f,
animationSpec = spring(
dampingRatio = 0.6f,
stiffness = Spring.StiffnessLow
)
)
scrollState.scrollTo(animatable.value.toInt())
}
}
但是,一切看起来都很不顺利,而且很慢。我做错了什么?
PS 这是为了提示用户该组件具有水平滚动。
您的代码无法正常工作,因为您
scrollState.scrollTo
在每个动画后手动调用 4 次。您应该scrollState.scrollTo
在更新时调用animatable.value
,例如:您无需手动制作弹跳动画,而是可以使用带有EaseOutBounce
tween
缓动的动画规范: