Оптимизируйте свои подборки
Сохраняйте и классифицируйте контент в соответствии со своими настройками.
Вы можете анимировать посимвольно внешний вид текста, чтобы он выглядел как эффект потокового набора текста, аналогичный тому, который производит пишущая машинка.
Совместимость версий
Для этой реализации требуется, чтобы в minSDK вашего проекта был установлен уровень API 21 или выше.
Зависимости
Анимация текста посимвольно
Этот код анимирует текст посимвольно. Он отслеживает индекс, чтобы контролировать, какая часть текста отображается. Отображаемый текст обновляется динамически, отображая только символы до текущего индекса. Наконец, переменная запускает анимацию при ее изменении.
@ComposableprivatefunAnimatedText(){valtext="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!valbreakIterator=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.valtypingDelayInMs=50LvarsubstringTextbyremember{mutableStateOf("")}LaunchedEffect(text){// Initial start delay of the typing animationdelay(1000)breakIterator.text=StringCharacterIterator(text)varnextIndex=breakIterator.next()// Iterate over the string, by index boundarywhile(nextIndex!=BreakIterator.DONE){substringText=text.subSequence(0,nextIndex).toString()// Go to the next logical character boundarynextIndex=breakIterator.next()delay(typingDelayInMs)}}Text(substringText)
BreakIterator корректно перебирает символы независимо от того, как они хранятся. Например, анимированные смайлы состоят из нескольких символов; BreakIterator гарантирует, что они обрабатываются как один символ, чтобы анимация не прерывалась.
LaunchedEffect запускает сопрограмму, чтобы ввести задержку между символами. Вы можете заменить блок кода прослушивателем кликов или любым другим событием, чтобы вызвать анимацию.
Компонуемый Text перерисовывается каждый раз, когда значение substringText обновляется.
Результаты
Рисунок 1. Текст и смайлы, анимированные посимвольно.
Коллекции, содержащие это руководство
Это руководство является частью тщательно подобранной коллекции быстрых руководств, охватывающих более широкие цели разработки Android:
Отображать текст
Текст — центральная часть любого пользовательского интерфейса. Узнайте, как можно представить текст в своем приложении, чтобы обеспечить приятный пользовательский опыт.
Контент и образцы кода на этой странице предоставлены по лицензиям. Java и OpenJDK – это зарегистрированные товарные знаки корпорации Oracle и ее аффилированных лиц.
Последнее обновление: 2025-02-06 UTC.
[[["Прост для понимания","easyToUnderstand","thumb-up"],["Помог мне решить мою проблему","solvedMyProblem","thumb-up"],["Другое","otherUp","thumb-up"]],[["Отсутствует нужная мне информация","missingTheInformationINeed","thumb-down"],["Слишком сложен/слишком много шагов","tooComplicatedTooManySteps","thumb-down"],["Устарел","outOfDate","thumb-down"],["Проблема с переводом текста","translationIssue","thumb-down"],["Проблемы образцов/кода","samplesCodeIssue","thumb-down"],["Другое","otherDown","thumb-down"]],["Последнее обновление: 2025-02-06 UTC."],[],[],null,["# Animate character-by-character the appearance of text\n\n\u003cbr /\u003e\n\nYou can animate, character-by-character, the appearance of text, so it looks\nlike a streaming typing effect, similar to what a typewriter would produce.\n\nVersion compatibility\n---------------------\n\nThis implementation requires that your project minSDK be set to API level 21 or\nhigher.\n\n### Dependencies\n\n### Kotlin\n\n\u003cbr /\u003e\n\n```kotlin\n implementation(platform(\"androidx.compose:compose-bom:2025.08.00\"))\n implementation(\"androidx.compose.material3:material3\")\n \n```\n\n\u003cbr /\u003e\n\n### Groovy\n\n\u003cbr /\u003e\n\n```groovy\n implementation platform('androidx.compose:compose-bom:2025.08.00')\n implementation 'androidx.compose.material3:material3'\n \n```\n\n\u003cbr /\u003e\n\nAnimate text character-by-character\n-----------------------------------\n\nThis code animates text character-by-character. It tracks an index to control\nhow much of the text is revealed. The displayed text updates dynamically to show\nonly the characters up to the current index. Finally, the variable runs the\nanimation when it changes.\n\n\n```kotlin\n@Composable\nprivate fun AnimatedText() {\n 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\"\n\n // Use BreakIterator as it correctly iterates over characters regardless of how they are\n // stored, for example, some emojis are made up of multiple characters.\n // You don't want to break up an emoji as it animates, so using BreakIterator will ensure\n // this is correctly handled!\n val breakIterator = remember(text) { BreakIterator.getCharacterInstance() }\n\n // Define how many milliseconds between each character should pause for. This will create the\n // illusion of an animation, as we delay the job after each character is iterated on.\n val typingDelayInMs = 50L\n\n var substringText by remember {\n mutableStateOf(\"\")\n }\n LaunchedEffect(text) {\n // Initial start delay of the typing animation\n delay(1000)\n breakIterator.text = StringCharacterIterator(text)\n\n var nextIndex = breakIterator.next()\n // Iterate over the string, by index boundary\n while (nextIndex != BreakIterator.DONE) {\n substringText = text.subSequence(0, nextIndex).toString()\n // Go to the next logical character boundary\n nextIndex = breakIterator.next()\n delay(typingDelayInMs)\n }\n }\n Text(substringText)https://github.com/android/snippets/blob/dd30aee903e8c247786c064faab1a9ca8d10b46e/compose/snippets/src/main/java/com/example/compose/snippets/animations/AnimationSnippets.kt#L939-L970\n```\n\n\u003cbr /\u003e\n\n### Key points about the code\n\n- [`BreakIterator`](/reference/android/icu/text/BreakIterator) correctly iterates over characters regardless of how they are stored. For example, animated emojis are made up of multiple characters; `BreakIterator` ensures that they're handled as a single character, so that the animation isn't broken.\n- [`LaunchedEffect`](/reference/kotlin/androidx/compose/runtime/package-summary#LaunchedEffect(kotlin.Any,kotlin.coroutines.SuspendFunction1)) starts a coroutine to introduce the delay between the characters. You can replace the code block with a click listener--or any other event--to trigger animation.\n- The [`Text`](/reference/kotlin/androidx/compose/material/package-summary#Text(kotlin.String,androidx.compose.ui.Modifier,androidx.compose.ui.graphics.Color,androidx.compose.ui.unit.TextUnit,androidx.compose.ui.text.font.FontStyle,androidx.compose.ui.text.font.FontWeight,androidx.compose.ui.text.font.FontFamily,androidx.compose.ui.unit.TextUnit,androidx.compose.ui.text.style.TextDecoration,androidx.compose.ui.text.style.TextAlign,androidx.compose.ui.unit.TextUnit,androidx.compose.ui.text.style.TextOverflow,kotlin.Boolean,kotlin.Int,kotlin.Int,kotlin.Function1,androidx.compose.ui.text.TextStyle)) composable re-renders every time the value of `substringText` is updated.\n\nResults\n-------\n\n\u003cbr /\u003e\n\n**Figure 1.** Text and emoji animated character-by-character.\n\n\u003cbr /\u003e\n\nCollections that contain this guide\n-----------------------------------\n\nThis guide is part of these curated Quick Guide collections that cover\nbroader Android development goals: \n\n### Display text\n\nText is a central piece of any UI. Find out different ways you can present text in your app to provide a delightful user experience. \n[Quick guide collection](/develop/ui/compose/quick-guides/collections/display-text) \n\n### Compose basics (video collection)\n\nThis series of videos introduces various Compose APIs, quickly showing you what's available and how to use them. \n[Quick guide collection](/develop/ui/compose/quick-guides/collections/compose-basics) \n\nHave questions or feedback\n--------------------------\n\nGo to our frequently asked questions page and learn about quick guides or reach out and let us know your thoughts. \n[Go to FAQ](/quick-guides/faq) [Leave feedback](https://issuetracker.google.com/issues/new?component=1573691&template=1993320)"]]