【问题标题】:How to make a widget invisible in Jetpack Compose?如何在 Jetpack Compose 中使小部件不可见?
【发布时间】:2021-06-23 20:27:34
【问题描述】:

我正在尝试在列中显示和隐藏ProgressIndicator。 问题是当我想隐藏ProgressIndicator 时,其他小部件之间的空间也会被删除(如View.GONE)但我想保持小部件大小(如View.INVISIBLE

示例:

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

        if (isLoading) {
            CircularProgressIndicator()
        }

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

我找到了一个解决方案,但我不确定它是否正确。

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

有没有其他方法可以像View.INVISIBLE 这样使小部件不可见?

如何获取小部件大小以设置Spacer 大小?

谢谢

【问题讨论】:

  • 你可以试试an alpha of 0
  • @CommonsWare 非常完美,谢谢。

标签: android kotlin android-jetpack-compose


【解决方案1】:

使用 Alpha Zero ,@commonsware 在 cmets 中提到了这一点,因为您不需要知道空间大小的大小,不像 Spacer() 可组合的需要特定大小和在某些情况下,这可能很难知道。

val commentsAlpha = if (condition) 1f else 0f
modifier = Modifier
            .alpha(commentsAlpha)

【讨论】:

  • 我试过这个:0f工作,它会不可见,但小部件有空白空间
  • @HariShankarS 这是不可见的预期行为。如果您想将其删除,它将“消失”。
【解决方案2】:

我正在使用以下方法: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"
                        }
                    )
                }

对于观察动画状态也很有用。

【讨论】:

    【解决方案3】:

    您的解决方案是正确的,但您也可以将进度指示器包装在预期大小的 Box 中

    Box(modifier = Modifier.height(40.dp) {
        if (condition) {
            CircularProgressIndicator()
        }
    }
    

    【讨论】:

    • 感谢您的回答。这个解决方案很好,但我必须手动设置Modifier.height()
    • 另外很重要的一点是,这样做总是会重新创建可组合的。然后,如果它内部有一些副作用(例如),所有这些影响都将被重新创建。小心。
    猜你喜欢
    • 2020-04-23
    • 1970-01-01
    • 2022-12-02
    • 2021-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多