我正在尝试将按钮的文本垂直和水平对齐到中心,默认情况下不存在。 我曾尝试使用“偏移”来定位按钮中的文本,但定位在各种设备尺寸上并不一致。
我的按钮代码是:
Button(
onClick = {
navController.navigate("fourth_screen")
},
modifier = Modifier.constrainAs(buttonSave) {
top.linkTo(glButtonSaveTop)
bottom.linkTo(glButtonSaveBottom)
start.linkTo(glLeft)
end.linkTo(glRight)
width = Dimension.fillToConstraints
height = Dimension.fillToConstraints
},
enabled = !errorMsg.value,
colors = if (query.value.text != ""){
ButtonDefaults.
buttonColors(backgroundColor = colorResource(id = R.color.voodlee_red))}
else {
ButtonDefaults.
buttonColors(backgroundColor = colorResource(id = R.color.gray))}
) {
Text(
"Save", color = colorResource(id = R.color.dark_blue),
fontSize = with(LocalDensity.current) {
dimensionResource(id = R.dimen._16ssp).toSp()
},
fontFamily = FontFamily(Font(R.font.poppins_medium)),
textAlign = TextAlign.Center,
modifier = Modifier.fillMaxSize().offset(y= (0.15).dp)) //offset for positioning
}
如何使按钮中的文本垂直和水平居中,适用于所有设备尺寸。
答案 0 :(得分:0)
您可以仅使用修饰符 align
将可组合对象居中:
Button(
onClick = {
navController.navigate("fourth_screen")
},
modifier = Modifier.constrainAs(buttonSave) {
top.linkTo(glButtonSaveTop)
bottom.linkTo(glButtonSaveBottom)
start.linkTo(glLeft)
end.linkTo(glRight)
width = Dimension.fillToConstraints
height = Dimension.fillToConstraints
},
enabled = !errorMsg.value,
colors = if (query.value.text != ""){
ButtonDefaults.
buttonColors(backgroundColor = colorResource(id = R.color.voodlee_red))}
else {
ButtonDefaults.
buttonColors(backgroundColor = colorResource(id = R.color.gray))}
) {
Text(
"Save", color = colorResource(id = R.color.dark_blue),
fontSize = with(LocalDensity.current) {
dimensionResource(id = R.dimen._16ssp).toSp()
},
fontFamily = FontFamily(Font(R.font.poppins_medium)),
textAlign = TextAlign.Center, // horizontal center of the text
modifier = Modifier.align(Alignment.CenterVertically) //vertical center of the Text composable
}