我试图将按钮的图标向左对齐并保持文本居中。任何想法如何实现?
我的可组合:
@Composable
fun CustomButton() {
MaterialTheme {
OutlinedButton(
onClick = {},
modifier = Modifier
.padding(12.dp),
colors = ButtonDefaults.buttonColors(backgroundColor = Color.White),
shape = RoundedCornerShape(4.dp)) {
Icon(
imageVector = Icons.Default.FavoriteBorder,
contentDescription = null,
modifier = Modifier.padding(start = 4.dp)
)
Text(text = "Like", color = Color.Grey)
}
}
}
答案 0 :(得分:1)
这是一种解决方法,但有效:
@Composable
fun CustomButton() {
MaterialTheme {
OutlinedButton(
onClick = {},
modifier = Modifier
.padding(12.dp)
.fillMaxWidth(),
colors = ButtonDefaults.buttonColors(backgroundColor = Color.White),
shape = RoundedCornerShape(4.dp)
) {
Box(
Modifier
.weight(1f)
.height(50.dp),
contentAlignment = Alignment.CenterStart
) {
Icon(
imageVector = Icons.Default.FavoriteBorder,
contentDescription = null,
modifier = Modifier.padding(start = 4.dp)
)
}
Box(
Modifier
.weight(1f)
.height(50.dp),
contentAlignment = Alignment.Center
) {
Text(text = "Like", color = Color.Gray)
}
Box(
Modifier
.weight(1f)
.height(50.dp)
) {
}
}
}
}
答案 1 :(得分:1)
如果您需要全宽按钮,请用 Box
包裹内容,然后在文本中添加 fillMaxWidth()
和 TextAlign.Center
@Composable
fun CustomButton() {
MaterialTheme {
OutlinedButton(
onClick = {},
modifier = Modifier.padding(12.dp),
colors = ButtonDefaults.buttonColors(backgroundColor = Color.White),
shape = RoundedCornerShape(4.dp)
) {
Box {
Text(
text = "Like",
color = Color.Gray,
modifier = Modifier.fillMaxWidth(),
textAlign = TextAlign.Center
)
Icon(
imageVector = Icons.Default.FavoriteBorder,
contentDescription = null,
modifier = Modifier.padding(start = 4.dp)
)
}
}
}
}
否则您可以创建自定义布局
@Composable
fun CustomButton() {
MaterialTheme {
OutlinedButton(
onClick = {},
modifier = Modifier.padding(12.dp),
colors = ButtonDefaults.buttonColors(backgroundColor = Color.White),
shape = RoundedCornerShape(4.dp)
) {
Layout(
content = {
Icon(Icons.Default.FavoriteBorder, null)
Text("Like", Modifier.padding(horizontal = 8.dp), Color.Gray)
},
measurePolicy = { measurables, constraints ->
val icon = measurables[0].measure(constraints)
val text = measurables[1].measure(constraints)
layout(
width = text.width + icon.width * 2,
height = maxOf(text.height, icon.height, constraints.minHeight)
) {
icon.placeRelative(0, 0)
text.placeRelative(icon.width, 0)
}
}
)
}
}
}