android 如何在Jetpack编写中处理文本的可见性?

dy1byipe  于 2023-01-07  发布在  Android
关注(0)|答案(4)|浏览(123)

我有这个文本:

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

如何显示和隐藏此组件?
我正在使用Jetpack合成版本**“1.0.0-alpha 03 '**

oknwwptz

oknwwptz1#

正如CommonsWare所说,composition作为一个声明性工具包,您可以将组件绑定到一个状态(例如:isVisible),则合成器将智能地决定哪些可合成对象依赖于该状态并重新合成它们。

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

此外,您还可以使用AnimatedVisibility()组合动画。

nzk0hqpo

nzk0hqpo2#

您可以简单地添加一个条件,例如:

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

例如:

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

如果您想要动画显示其内容的出现和消失,可以使用**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") }
}
qvsjd97n

qvsjd97n3#

如上所述,您可以像这样使用AnimatedVisibility:

AnimatedVisibility(visible = yourCondition) { Text(text = getString(R.string.yourString)) }
35g0bw71

35g0bw714#

/**
 * @param visible if false content is invisible ie. space is still occupied
 */
@Composable
fun Visibility(
    visible: Boolean,
    content: @Composable () -> Unit
) {
    val contentSize = remember { mutableStateOf(IntSize.Zero) }

    Box(modifier = Modifier
        .onSizeChanged { size -> contentSize.value = size }) {
        if (visible || contentSize.value == IntSize.Zero) {
            content()
        } else {
            Spacer(modifier = Modifier.size(contentSize.value.width.pxToDp(), contentSize.value.height.pxToDp()))
        }
    }
}

fun Int.pxToDp(): Dp {
    return (this / getSystem().displayMetrics.density).dp
}

用法:

Visibility(text.value.isNotEmpty()) {
    IconButton(
        onClick = { text.value = "" },
        modifier = Modifier
            .padding(bottom = 8.dp)
            .height(30.dp),
    ) {
        Icon(Icons.Filled.Close, contentDescription = "Clear text")
    }
}

相关问题