如何使 Jetpack Compose 中的小部件不可见?

Ehs*_*msz 33 android kotlin android-jetpack-compose

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") })    
    }
}
Run Code Online (Sandbox Code Playgroud)

我找到了解决方案,但我不确定这是否是正确的方法。

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

Run Code Online (Sandbox Code Playgroud)

还有其他方法可以使小部件不可见吗View.INVISIBLE

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

谢谢

هيث*_*يثم 29

使用 Alpha Zero,这是 @commonsware 的评论中提到的,因为您不需要知道空间大小的大小,这与需要特定大小的 Spacer() 可组合项不同,在某些情况下这可能很难知道。

val commentsAlpha = if (condition) 1f else 0f
modifier = Modifier
            .alpha(commentsAlpha)
Run Code Online (Sandbox Code Playgroud)

  • 请注意,任何按钮或类似按钮即使不可见也将保持可点击! (13认同)
  • @MarioHuizinga`.clickable(enabled = condition){ onClick() }` 很容易获得 (2认同)

Haw*_*ike 6

您可以使用自定义布局修饰符,它定义要使其不可见的可组合项的空白区域。它还可以防止在不可见时接收任何触摸事件。

fun Modifier.visibility(visible: Boolean): Modifier {
    return layout { measurable, constraints ->
        val placeable = measurable.measure(constraints)

        layout(placeable.width, placeable.height) {
            if (visible) {
                // place this item in the original position
                placeable.placeRelative(0, 0) 
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Fra*_*esc 2

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

Box(modifier = Modifier.height(40.dp) {
    if (condition) {
        CircularProgressIndicator()
    }
}
Run Code Online (Sandbox Code Playgroud)