如何使用Android Jetpack Compose实现搜索框占位符文本动画?
实现Google Play风格的SearchBar占位符动画
你的当前实现仅用基础Crossfade切换文本,缺少Google Play动画里细腻的缩放和交错过渡效果。以下是优化后的实现,还原更贴近原版的平滑动效:
import androidx.compose.animation.animateFloatAsState import androidx.compose.animation.core.FastOutSlowInEasing import androidx.compose.animation.core.tween import androidx.compose.foundation.layout.Box import androidx.compose.material3.SearchBar import androidx.compose.material3.Text 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.scale // 在你的Composable中使用 var isInitialPlaceholder by remember { mutableStateOf(true) } // 初始文本的动画参数:透明度从1到0,缩放从1到0.8 val initialAlpha by animateFloatAsState( targetValue = if (isInitialPlaceholder) 1f else 0f, animationSpec = tween(durationMillis = 300, easing = FastOutSlowInEasing) ) val initialScale by animateFloatAsState( targetValue = if (isInitialPlaceholder) 1f else 0.8f, animationSpec = tween(durationMillis = 300, easing = FastOutSlowInEasing) ) // 目标文本的动画参数:延迟100ms启动,透明度从0到1,缩放从0.8到1 val targetAlpha by animateFloatAsState( targetValue = if (!isInitialPlaceholder) 1f else 0f, animationSpec = tween(durationMillis = 300, delayMillis = 100, easing = FastOutSlowInEasing) ) val targetScale by animateFloatAsState( targetValue = if (!isInitialPlaceholder) 1f else 0.8f, animationSpec = tween(durationMillis = 300, delayMillis = 100, easing = FastOutSlowInEasing) ) LaunchedEffect(Unit) { delay(1000) // 初始显示1秒后触发动画 isInitialPlaceholder = false } SearchBar( query = "", onQueryChange = {}, onSearch = {}, active = false, onActiveChange = {}, placeholder = { Box(contentAlignment = Alignment.CenterStart) { // 初始占位文本:"Google Play" Text( text = "Google Play", alpha = initialAlpha, modifier = Modifier.scale(initialScale) ) // 切换后的占位文本:"Search..." Text( text = "Search...", alpha = targetAlpha, modifier = Modifier.scale(targetScale) ) } } ) { // SearchBar内容区域(按需添加) }
关键优化点:
- 缩放动画:初始文本缩小淡出,目标文本放大淡入,还原Google Play的细腻过渡质感
- 交错时序:目标文本延迟启动动画,避免切换过于生硬
- 自然缓动:使用
FastOutSlowInEasing实现符合真实物理规律的动效曲线 - 对齐保持:通过
Box和Alignment.CenterStart确保文本切换时位置不偏移
你可以按需调整动画时长(durationMillis)、延迟时间(delayMillis)或缩放比例,完全匹配Google Play的视觉效果。
内容的提问来源于stack exchange,提问作者Curious Head
相关产品推荐
相关产品推荐

