Tạo hiệu ứng động cho giao diện văn bản theo từng ký tự
Sử dụng bộ sưu tập để sắp xếp ngăn nắp các trang
Lưu và phân loại nội dung dựa trên lựa chọn ưu tiên của bạn.
Bạn có thể tạo ảnh động, từng ký tự một, cho giao diện văn bản, để văn bản trông giống như hiệu ứng nhập trực tuyến, tương tự như hiệu ứng mà máy đánh chữ tạo ra.
Khả năng tương thích của phiên bản
Phương thức triển khai này yêu cầu bạn phải đặt minSDK của dự án thành API cấp 21 trở lên.
Phần phụ thuộc
Tạo hiệu ứng động cho văn bản theo từng ký tự
Mã này tạo ảnh động cho văn bản theo từng ký tự. Thành phần này theo dõi một chỉ mục để kiểm soát lượng văn bản được hiển thị. Văn bản hiển thị sẽ tự động cập nhật để chỉ hiển thị các ký tự cho đến chỉ mục hiện tại. Cuối cùng, biến này sẽ chạy ảnh động khi thay đổi.
@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 lặp lại chính xác các ký tự bất kể cách lưu trữ các ký tự đó. Ví dụ: biểu tượng cảm xúc động được tạo thành từ nhiều ký tự; BreakIterator đảm bảo rằng chúng được xử lý dưới dạng một ký tự duy nhất để ảnh động không bị hỏng.
LaunchedEffect bắt đầu một coroutine để tạo độ trễ giữa các ký tự. Bạn có thể thay thế khối mã bằng trình nghe nhấp chuột hoặc bất kỳ sự kiện nào khác để kích hoạt ảnh động.
Thành phần kết hợp Text sẽ kết xuất lại mỗi khi giá trị của substringText được cập nhật.
Kết quả
Hình 1. Văn bản và biểu tượng cảm xúc động theo từng ký tự.
Các bộ sưu tập chứa hướng dẫn này
Hướng dẫn này là một phần của các bộ sưu tập Hướng dẫn nhanh được tuyển chọn này, bao gồm các mục tiêu phát triển Android rộng hơn:
Văn bản hiển thị
Văn bản là phần chính của mọi giao diện người dùng. Tìm hiểu các cách khác nhau để trình bày văn bản trong ứng dụng nhằm mang lại trải nghiệm thú vị cho người dùng.
Nội dung và mã mẫu trên trang này phải tuân thủ các giấy phép như mô tả trong phần Giấy phép nội dung. Java và OpenJDK là nhãn hiệu hoặc nhãn hiệu đã đăng ký của Oracle và/hoặc đơn vị liên kết của Oracle.
Cập nhật lần gần đây nhất: 2025-02-06 UTC.
[[["Dễ hiểu","easyToUnderstand","thumb-up"],["Giúp tôi giải quyết được vấn đề","solvedMyProblem","thumb-up"],["Khác","otherUp","thumb-up"]],[["Thiếu thông tin tôi cần","missingTheInformationINeed","thumb-down"],["Quá phức tạp/quá nhiều bước","tooComplicatedTooManySteps","thumb-down"],["Đã lỗi thời","outOfDate","thumb-down"],["Vấn đề về bản dịch","translationIssue","thumb-down"],["Vấn đề về mẫu/mã","samplesCodeIssue","thumb-down"],["Khác","otherDown","thumb-down"]],["Cập nhật lần gần đây nhất: 2025-02-06 UTC."],[],[],null,["\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\nThis implementation requires that your project minSDK be set to API level 21 or\nhigher.\n\nDependencies\n\nAnimate text character-by-character\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/5673ffc60b614daf028ee936227128eb8c4f9781/compose/snippets/src/main/java/com/example/compose/snippets/animations/AnimationSnippets.kt#L939-L970\n```\n\n\u003cbr /\u003e\n\nKey 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\u003cbr /\u003e\n\n**Figure 1.** Text and emoji animated character-by-character.\n\n\u003cbr /\u003e\n\nCollections that contain this guide\n\nThis guide is part of these curated Quick Guide collections that cover\nbroader Android development goals: \n\nDisplay text \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\nCompose basics (video collection) \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 \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)"]]