Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a widget invisible in Jetpack Compose?

I'm trying to show and hide ProgressIndicator in a column. the problem is when I want to hide the ProgressIndicator, the space between other widgets will be removed too (like View.GONE) but I want to keep widget size (like View.INVISIBLE)

example:

@Composable
fun Main(isLoading: Boolean) {
    Column {
        Text(text = "Text")

        if (isLoading) {
            CircularProgressIndicator()
        }

        Button(onClick = { /*clicked*/ }, content = { Text(text = "Button") })    
    }
}

I found a solution but I'm not sure if it's the right way.

if (isLoading) {
    CircularProgressIndicator()
} else {
    Spacer(modifier = Modifier.height(40.dp))
}

Is there any other way for making the widget invisible like View.INVISIBLE?

How can I get widget size to set Spacer size?

Thanks

like image 254
Ehsan msz Avatar asked Oct 15 '22 20:10

Ehsan msz


3 Answers

Use Alpha Zero , this is mentioned in the comments by @commonsware, as you do not need to know the size about the space size, unlike to Spacer() composable which needs a specific size and in some cases this may be hard to know.

val commentsAlpha = if (condition) 1f else 0f
modifier = Modifier
            .alpha(commentsAlpha)
like image 90
هيثم Avatar answered Oct 19 '22 09:10

هيثم


I am using the following method: AnimatedVisibility https://developer.android.com/jetpack/compose/animation#animatedvisibility

 // Create a MutableTransitionState<Boolean> for the AnimatedVisibility.
                val state = remember {
                    MutableTransitionState(false).apply {
                        // Start the animation immediately.
                        targetState = true
                    }
                }
                Column {
                    AnimatedVisibility(visibleState = state) {
                        Text(text = "Hello, world!")
                    }

                    // Use the MutableTransitionState to know the current animation state
                    // of the AnimatedVisibility.
                    Text(
                        text = when {
                            state.isIdle && state.currentState -> "Visible"
                            !state.isIdle && state.currentState -> "Disappearing"
                            state.isIdle && !state.currentState -> "Invisible"
                            else -> "Appearing"
                        }
                    )
                }

enter image description here

It is also useful for observing the animation state.

like image 22
Hari Shankar S Avatar answered Oct 19 '22 09:10

Hari Shankar S


Your solution is correct, but you could also wrap your progress indicator in a Box of the expected size

Box(modifier = Modifier.height(40.dp) {
    if (condition) {
        CircularProgressIndicator()
    }
}
like image 2
Francesc Avatar answered Oct 19 '22 11:10

Francesc