您可以逐个字符地为文本添加动画效果,使其看起来像流式输入效果,类似于打字机产生的效果。
结果
版本兼容性
此实现要求将项目的 minSDK 设置为 API 级别 21 或更高级别。
依赖项
逐个字符地为文字添加动画效果
此代码可逐个字符地为文本添加动画效果。它会跟踪一个索引,以控制显示多少文本。显示的文字会动态更新,仅显示当前索引之前的字符。最后,变量会在发生变化时运行动画。
@Composable private fun AnimatedText() { val text = "This text animates as though it is being typed \uD83E\uDDDE\u200D♀\uFE0F \uD83D\uDD10 \uD83D\uDC69\u200D❤\uFE0F\u200D\uD83D\uDC68 \uD83D\uDC74\uD83C\uDFFD" // Use BreakIterator as it correctly iterates over characters regardless of how they are // stored, for example, some emojis are made up of multiple characters. // You don't want to break up an emoji as it animates, so using BreakIterator will ensure // this is correctly handled! val breakIterator = remember(text) { BreakIterator.getCharacterInstance() } // Define how many milliseconds between each character should pause for. This will create the // illusion of an animation, as we delay the job after each character is iterated on. val typingDelayInMs = 50L var substringText by remember { mutableStateOf("") } LaunchedEffect(text) { // Initial start delay of the typing animation delay(1000) breakIterator.text = StringCharacterIterator(text) var nextIndex = breakIterator.next() // Iterate over the string, by index boundary while (nextIndex != BreakIterator.DONE) { substringText = text.subSequence(0, nextIndex).toString() // Go to the next logical character boundary nextIndex = breakIterator.next() delay(typingDelayInMs) } } Text(substringText)
代码要点
BreakIterator会正确地迭代字符,无论这些字符的存储方式如何。例如,动画表情符号由多个字符组成;BreakIterator可确保将它们视为单个字符进行处理,以免动画中断。LaunchedEffect启动一个协程,以在字符之间引入延迟。您可以使用点击监听器(或其他任何事件)替换该代码块,以触发动画。- 每次更新
substringText的值时,Text可组合项都会重新渲染。
包含本指南的合集
本指南属于以下精选的快速指南合集,涵盖了更广泛的 Android 开发目标:
显示文本
文字对任何界面都属于核心内容。了解您可以在应用中以哪些不同的方式呈现文字,从而提供愉悦的用户体验。
Compose 基础知识(视频集)
此系列视频介绍了各种 Compose API,可让您快速了解可用的 API 及其使用方法。
有问题或想提供反馈
前往我们的常见问题解答页面,了解有关快速指南的信息;或者联系我们并告知您的想法。