android - 在 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.Center
TextView 的文本居中,但它只是水平居中。我怎样才能使它也垂直居中?
解决方案
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
改用。
推荐阅读
- mysql - 拥有最近帖子的用户将比拥有旧帖子的用户更快地返回结果
- java - Java.time 从偏移量到时区名称
- c# - 如何为具有两个参数的Controller方法编写单元测试以及需要测试哪些场景?
- csv - 如何从 Gnuplot 中的 CSV 文件中绘制曲线?
- python - 即使在 Python 3.6 中安装 Xlrd 后也会出错
- ruby-on-rails - Ruby on Rails 5 随机 NameError:控制台中命名空间模型上的未初始化常量
- c# - 替换时区
- sql - 查看应用程序发送的 SQL 语句历史记录?
- vba - 宏结束,内容仍被选中
- javascript - 无法将 obj 实例化为文件并在另一个文件中使用它