Skip to content

Commit 5e2384b

Browse files
authored
Merge pull request #346 from android/animate-char-by-char
Code snippet for Compose doc at https://developer.android.com/quick-g…
2 parents 831e1f6 + c5c65e1 commit 5e2384b

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

compose/snippets/src/main/java/com/example/compose/snippets/animations/AnimationSnippets.kt

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,9 @@ import androidx.compose.ui.unit.Dp
109109
import androidx.compose.ui.unit.IntSize
110110
import androidx.compose.ui.unit.dp
111111
import com.example.compose.snippets.R
112+
import java.text.BreakIterator
113+
import java.text.StringCharacterIterator
114+
import kotlinx.coroutines.delay
112115

113116
/*
114117
* Copyright 2023 The Android Open Source Project
@@ -820,3 +823,39 @@ private fun Expanded() {
820823
@Composable
821824
private fun ContentIcon() {
822825
}
826+
827+
// [START android_compose_animations_char_by_char]
828+
@Composable
829+
private fun AnimatedText() {
830+
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"
831+
832+
// Use BreakIterator as it correctly iterates over characters regardless of how they are
833+
// stored, for example, some emojis are made up of multiple characters.
834+
// You don't want to break up an emoji as it animates, so using BreakIterator will ensure
835+
// this is correctly handled!
836+
val breakIterator = remember(text) { BreakIterator.getCharacterInstance() }
837+
838+
// Define how many milliseconds between each character should pause for. This will create the
839+
// illusion of an animation, as we delay the job after each character is iterated on.
840+
val typingDelayInMs = 50L
841+
842+
var substringText by remember {
843+
mutableStateOf("")
844+
}
845+
LaunchedEffect(text) {
846+
// Initial start delay of the typing animation
847+
delay(1000)
848+
breakIterator.text = StringCharacterIterator(text)
849+
850+
var nextIndex = breakIterator.next()
851+
// Iterate over the string, by index boundary
852+
while (nextIndex != BreakIterator.DONE) {
853+
substringText = text.subSequence(0, nextIndex).toString()
854+
// Go to the next logical character boundary
855+
nextIndex = breakIterator.next()
856+
delay(typingDelayInMs)
857+
}
858+
}
859+
Text(substringText)
860+
// [END android_compose_animations_char_by_char]
861+
}

0 commit comments

Comments
 (0)