逐字符动画方式显示文本

您可以逐字符地动画方式显示文本,使其看起来像流式打字效果,类似于打字机产生的效果。

版本兼容性

此实现要求您的项目 minSDK 设置为 API level 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 启动一个协程来引入字符之间的延迟。您可以将代码块替换为点击监听器或任何其他事件来触发动画。
  • Text 可组合函数在每次 substringText 的值更新时重新渲染。

结果

图 1. 逐字符动画方式显示的文本和表情符号。

包含本指南的合集

本指南是这些精选快速指南合集的一部分,这些合集涵盖了更广泛的 Android 开发目标

文本是任何界面的核心部分。了解在应用中呈现文本的不同方式,以提供愉悦的用户体验。
本视频系列介绍了各种 Compose API,快速向您展示有哪些可用 API 以及如何使用它们。

有疑问或反馈

请访问我们的常见问题页面,了解快速指南,或与我们联系并告知您的想法。