Puoi animare l'aspetto del testo carattere per carattere, in modo che sembri un effetto di digitazione in streaming, simile a quello prodotto da una macchina da scrivere.
Risultati
Compatibilità con la versione
Questa implementazione richiede che il minSDK del progetto sia impostato sul livello API 21 o superiore.
Dipendenze
Animare il testo carattere per carattere
Questo codice anima il testo carattere per carattere. Monitora un indice per controllare la quantità di testo visualizzata. Il testo visualizzato viene aggiornato dinamicamente per mostrare solo i caratteri fino all'indice corrente. Infine, la variabile esegue l'animazione quando cambia.
@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)
Punti chiave sul codice
BreakIteratorscorre correttamente i caratteri indipendentemente dalla modalità di archiviazione. Ad esempio, le emoji animate sono composte da più caratteri;BreakIteratorgarantisce che vengano gestite come un singolo carattere, in modo che l'animazione non venga interrotta.LaunchedEffectavvia una coroutine per introdurre il ritardo tra i caratteri. Puoi sostituire il blocco di codice con un listener di clic o qualsiasi altro evento per attivare l'animazione.- Il
Textcomposable viene eseguito di nuovo ogni volta che il valore disubstringTextviene aggiornato.
Raccolte che contengono questa guida
Questa guida fa parte di queste raccolte di guide rapide curate che riguardano obiettivi di sviluppo Android più ampi:
Testo visualizzato