I want to use AnimatedContent
to switch between TextField
and Text
components.
I am using text != null
as targetState
, such that Text
is shown when targetState
is null
, and TextField
otherwise.
Following is the implementation:
@OptIn(ExperimentalAnimationApi::class, ExperimentalMaterial3Api::class)
@Preview
@Composable
private fun ViewTest() {
val durationMillis = 2000
var text by remember { mutableStateOf<String?>(null) }
Surface {
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
) {
AnimatedContent(
targetState = text != null,
label = "",
transitionSpec = {
ContentTransform(
targetContentEnter = fadeIn(animationSpec = tween(durationMillis)),
initialContentExit = fadeOut(animationSpec = tween(durationMillis)),
sizeTransform = SizeTransform(sizeAnimationSpec = { _, _ -> tween(durationMillis) })
)
}
) { show ->
if (show)
TextField(
value = text ?: "",
onValueChange = { text = it },
placeholder = { Text(text = "Search") }
)
else
Text(text = "Title")
}
AnimatedContent(targetState = text != null, label = "") { show ->
if (show)
IconButton(onClick = { text = null }) {
Icon(Icons.Rounded.Clear, contentDescription = null)
}
else
IconButton(onClick = { text = "" }) {
Icon(Icons.Rounded.Search, contentDescription = null)
}
}
}
}
}
However, when targetState
is non-empty, and is set to null
from the IconButton
, following is the animation:
I want that the intermediate placeholder
should not be shown, but I am not able to do that. If I use targetState = text
, then it doesn't work at all.
How can I transition directly without showing the placeholder
text "Search"?
Try this.