คุณทำให้ข้อความเคลื่อนไหวทีละตัวได้เพื่อให้ดูเหมือนเอฟเฟกต์การพิมพ์แบบเรียลไทม์ ซึ่งคล้ายกับที่เครื่องพิมพ์ดีดจะแสดง
ความเข้ากันได้ของเวอร์ชัน
การใช้งานนี้กำหนดให้โปรเจ็กต์ของคุณตั้งค่า minSDK เป็น API ระดับ 21 ขึ้นไป
ทรัพยากร Dependency
ทำให้ข้อความเคลื่อนไหวทีละตัวอักษร
โค้ดนี้จะแสดงภาพเคลื่อนไหวของข้อความทีละตัวอักษร โดยจะติดตามดัชนีเพื่อควบคุมปริมาณข้อความที่จะแสดง ข้อความที่แสดงจะอัปเดตแบบไดนามิกเพื่อแสดงเฉพาะอักขระจนถึงดัชนีปัจจุบัน สุดท้ายตัวแปรจะเรียกใช้ภาพเคลื่อนไหวเมื่อมีการเปลี่ยนแปลง
@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
ผลลัพธ์
คอลเล็กชันที่มีคู่มือนี้
คู่มือนี้เป็นส่วนหนึ่งของคอลเล็กชันคู่มือฉบับย่อที่มีการดูแลจัดการ ซึ่งครอบคลุมเป้าหมายการพัฒนา Android ที่กว้างขึ้น ดังนี้
![](https://developer.android.google.cn/static/images/quick-guides/collection-illustration.png?hl=th)
ข้อความที่แสดง
![](https://developer.android.google.cn/static/images/quick-guides/collection-illustration.png?hl=th)