Skip to content

Instantly share code, notes, and snippets.

@kasem-sm
Created April 12, 2022 19:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kasem-sm/694fbc82c142ef5b50846c19b8927c01 to your computer and use it in GitHub Desktop.
Save kasem-sm/694fbc82c142ef5b50846c19b8927c01 to your computer and use it in GitHub Desktop.
Animated Placeholder with Jetpack Compose
@Composable
fun AnimatedPlaceholder(
hints: List<String>,
textStyle: FontFamily = LocalSlimeFont.current.medium,
textColor: Color = MaterialTheme.colorScheme.onSurfaceVariant,
) {
val iterator = hints.listIterator()
val target by produceState(initialValue = hints.first()) {
iterator.doWhenHasNextOrPrevious {
value = it
}
}
AnimatedContent(
targetState = target,
transitionSpec = { ScrollAnimation() }
) { str ->
Text(
text = str,
fontFamily = textStyle,
color = textColor,
fontSize = 14.withScale(),
)
}
}
suspend fun <T> ListIterator<T>.doWhenHasNextOrPrevious(
delayMills: Long = 3000,
doWork: suspend (T) -> Unit
) {
while (hasNext() || hasPrevious()) {
while (hasNext()) {
delay(delayMills)
doWork(next())
}
while (hasPrevious()) {
delay(delayMills)
doWork(previous())
}
}
}
object ScrollAnimation {
operator fun invoke(): ContentTransform {
return slideInVertically(
initialOffsetY = { 50 },
animationSpec = tween()
) + fadeIn() with slideOutVertically(
targetOffsetY = { -50 },
animationSpec = tween()
) + fadeOut()
}
}
@Composable
fun SearchBar(
modifier: Modifier = Modifier,
query: String,
onQueryChange: (String) -> Unit,
) {
SlimeTextField(
modifier = modifier,
input = query,
onTextChange = onQueryChange,
placeholderContent = {
AnimatedPlaceholder(
hints = listOf(
stringResource(id = R.string.article_search_txt_1),
stringResource(id = R.string.article_search_txt_2),
"Search your favourite topic",
),
)
},
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment