首页 > 解决方案 > 在 TextView 中以 Compose 的宽度和高度居中文本

问题描述

我有这个可组合的:

@Composable
fun MyApp() {

    var isSelected by remember { mutableStateOf(false) }
    val backgroundColor by animateColorAsState(if (isSelected) Color.Red else Color.Transparent)

    Column(
        modifier = Modifier
            .fillMaxSize(),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Text(
            text = "Hello",
            modifier = Modifier.background(color = backgroundColor)
                .clickable(onClick = { isSelected = !isSelected })
                .width(100.dp)
                .height(40.dp),
            textAlign = TextAlign.Center,

        )
    }
}

我希望TextAlign.CenterTextView 的文本居中,但它只是水平居中。我怎样才能使它也垂直居中?

标签: androidkotlinandroid-jetpack-compose

解决方案


TextAlign.Center只能水平居中您的内容。

要将其垂直居中,您需要将其放置在容器中,例如Box,并将内容对齐和大小修饰符应用于此容器:

Column(
    modifier = Modifier
        .fillMaxSize(),
    verticalArrangement = Arrangement.Center,
    horizontalAlignment = Alignment.CenterHorizontally
) {
    Box(
        contentAlignment = Alignment.Center,
        modifier = Modifier
            .width(100.dp)
            .height(40.dp)
            .background(color = backgroundColor)
            .clickable(onClick = { isSelected = !isSelected })
    ) {
        Text(
            text = "Hello",
            textAlign = TextAlign.Center
        )
    }
}

另外我想说的是,这通常是一种不好的做法,因为当用户在手机辅助功能设置中增加文本大小时,您Text可能不再适合您的盒子。考虑padding改用。


推荐阅读