能否使用Jetpack Compose实现类似示例GIF的倒计时动画?
用Android Jetpack Compose实现数字倒计时动画(4到0)
当然可以实现这种从4到0的数字倒计时动画,用Jetpack Compose的状态管理和动画API就能轻松搞定。下面是一个完整的实现示例:
import androidx.compose.animation.core.animateIntAsState import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp import kotlinx.coroutines.delay @Composable fun CountdownTimer() { // 保存当前倒计时数字的状态 var currentCount by remember { mutableStateOf(4) } // 为数字变化添加平滑过渡动画 val animatedCount by animateIntAsState( targetValue = currentCount, label = "Countdown Animation" ) Column( modifier = Modifier.fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Text( text = animatedCount.toString(), fontSize = 80.sp, fontWeight = FontWeight.Bold ) } // 启动倒计时协程,仅在组件首次组合时触发 LaunchedEffect(Unit) { repeat(4) { delay(1000) currentCount-- } // 倒计时结束后可添加后续逻辑,如页面跳转、弹窗提示等 } }
关键部分说明:
mutableStateOf+remember:用来持久化倒计时的当前数字,状态变化会自动触发Compose组件重组。animateIntAsState:让数字从当前值过渡到目标值时产生平滑的动画效果,替代生硬的数字切换。LaunchedEffect:在组件首次加载时启动协程,每隔1秒更新一次倒计时数字,直到数值减至0。
如果需要更丰富的视觉效果(比如数字缩放、颜色渐变),可以扩展动画逻辑,比如给数字添加缩放震动效果:
val scale by animateFloatAsState( targetValue = if (animatedCount == currentCount) 1f else 1.2f, label = "Scale Animation" ) Text( text = animatedCount.toString(), fontSize = 80.sp, fontWeight = FontWeight.Bold, modifier = Modifier.scale(scale) )
内容的提问来源于stack exchange,提问作者Vahit Keskin
相关产品推荐
相关产品推荐

