Skip to content

Commit 69588da

Browse files
committed
1 parent 351fcb4 commit 69588da

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

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

Lines changed: 38 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 kotlinx.coroutines.delay
113+
import java.text.BreakIterator
114+
import java.text.StringCharacterIterator
112115

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

0 commit comments

Comments
 (0)