I have a Text
composable within a Box
:
Box(modifier = Modifier)
) {
Text(text = "BlaBla" )
}
How can show the Box/Text for a few seconds, only?
I have a Text
composable within a Box
:
Box(modifier = Modifier)
) {
Text(text = "BlaBla" )
}
How can show the Box/Text for a few seconds, only?
You can use LaunchedEffect
and delay with a boolean flag and set it false after time specified
@Composable
private fun TimedLayout() {
var show by remember { mutableStateOf(true) }
LaunchedEffect(key1 = Unit){
delay(5000)
show = false
}
Column(modifier=Modifier.fillMaxSize()) {
Text("Box showing: $show")
if(show){
Box{
Text(text = "BlaBla" )
}
}
}
}
There are tons of way you can achieve this, for instance:
You can use AnimatedVisibility
in case you want to choose which animation you want.
Example:
AnimatedVisibility(visible = yourFlag) {
Box{
Text(text = "BlaBla")
}
}
If you are using a ViewModel
or any pattern and you can observe you can create two states and then inside of the ViewModel
/ Presenter
/ Whatever you start the timer you want (doing this you can test it):
sealed class TextState {
object Visible: TextState()
object Invisible: TextState()
}
And then inside the @Composable
you do this
val state by presenter.uiState.collectAsState()
when (val newState = state) {
Visible -> {}
Invisible -> {}
}
You can change it also playing with the Alpha
Modifier.alpha(if(isVisible) 1f else 0f)
Another valid option is what @Thracian commented, using Side-Effects
for example :
@Composable
fun YourComposable() {
LaunchedEffect(key1 = Unit, block = {
try {
initTimer(SECONDS_HERE) {
//Timer has passed so you can show or hide
}
} catch(e: Exception) {
//Something wrong happened with the timer
}
})
}
suspend fun initTimer(time: Long, onEnd: () -> Unit) {
delay(timeMillis = time)
onEnd()
}