How to handle visibility of a Text in Jetpack Compose?

12,975

Solution 1

As CommonsWare stated, compose being a declarative toolkit you tie your component to a state (for ex: isVisible), then compose will intelligently decide which composables depend on that state and recompose them. For ex:

@Composable
fun MyText(isVisible: Boolean){
  if(isVisible){
     Text(text = stringResource(id = R.string.hello))
  }
}

Also you could use the AnimatedVisibility() composable for animations.

Solution 2

With 1.0.x you can simply add a condition like:

  if(isVisible){
     Text("....")
  }

Something like:

var visible by remember { mutableStateOf(true) }
Column() {
    Text("Text")
    Button(onClick = { visible = !visible }) { Text("Toggle") }
}

If you want to animate the appearance and disappearance of its content you can use the AnimatedVisibility

var visible by remember { mutableStateOf(true) }
Column() {
    AnimatedVisibility(
        visible = visible,
        enter = fadeIn(
            // Overwrites the initial value of alpha to 0.4f for fade in, 0 by default
            initialAlpha = 0.4f
        ),
        exit = fadeOut(
            // Overwrites the default animation with tween
            animationSpec = tween(durationMillis = 250)
        )
    ) {
        // Content that needs to appear/disappear goes here:
        Text("....")
    }
    Button(onClick = { visible = !visible }) { Text("Toggle") }
}

Solution 3

As stated above, you could use AnimatedVisibility like:

AnimatedVisibility(visible = yourCondition) { Text(text = getString(R.string.yourString)) }
Share:
12,975
Agna JirKon Rx
Author by

Agna JirKon Rx

“We, the unwilling, led by the unknowing, are doing the impossible for the ungrateful. We have done so much, for so long, with so little, we are now qualified to do anything with nothing.” ― Konstantin Josef Jireček

Updated on June 15, 2022

Comments

  • Agna JirKon Rx
    Agna JirKon Rx about 2 years

    I have this Text:

    Text(
        text = stringResource(id = R.string.hello)
    )
    

    How can I show and hide this component?

    I'm using Jetpack Compose version '1.0.0-alpha03'