chanjungskim
03/09/2023, 3:51 AMPablichjenkov
03/09/2023, 4:08 AMchanjungskim
03/09/2023, 4:16 AMval transition = updateTransition(targetState = text, label = text)
val caretIndex by transition.animateInt(
transitionSpec = {
tween(durationMillis = duration.toInt()*text.length)
},
label = "caretIndex"
) { targetText ->
Log.d("aos", "targetText: $targetText")
targetText.length
}
But this one also doesn't clear the previous value.chanjungskim
03/09/2023, 4:41 AM@Composable
fun TypeAnimationText(
text: String,
duration: Long,
modifier: Modifier = Modifier,
style: TextStyle = TextStyle.Default,
color: androidx.compose.ui.graphics.Color = Color.Black,
) {
val transition = updateTransition(targetState = text, label = text)
val caretIndex by transition.animateInt(
transitionSpec = {
tween(durationMillis = duration.toInt()*text.length)
},
label = "caretIndex"
) { targetText ->
Log.d("aos", "targetText: $targetText")
targetText.length
}
// decompose caretIndex to 0
Text(
text = buildAnnotatedString {
withStyle(style = SpanStyle(color = color)) {
append(text.substring(0, caretIndex))
}
withStyle(style = SpanStyle(color = Color.Transparent)) {
append(text.substring(caretIndex, text.length))
}
},
style = style,
modifier = modifier
)
}
Pablichjenkov
03/09/2023, 4:45 AMchanjungskim
03/09/2023, 6:52 AM@Composable
fun TypeAnimationText(
text: String,
speed: Int,
modifier: Modifier = Modifier,
style: TextStyle = TextStyle.Default,
color: androidx.compose.ui.graphics.Color = Color.Black,
) {
if(text.isEmpty()) return
val animatable = remember { Animatable(0f) }
LaunchedEffect(key1 = text) {
animatable.animateTo(
targetValue = text.length.toFloat(),
animationSpec = tween(durationMillis = speed * text.length)
)
}
val index = animatable.value.toInt()
Text(
text = buildAnnotatedString {
withStyle(style = SpanStyle(color = color)) {
append(text.substring(0, index.toInt()))
}
withStyle(style = SpanStyle(color = Color.Transparent)) {
append(text.substring(index.toInt(), text.length))
}
},
style = style,
modifier = modifier
)
}