如何将按钮中的图标向左对齐并保持文本居中

Pra*_* P. 6 android android-jetpack-compose android-compose-button android-jetpack-compose-button

我试图将按钮的图标向左对齐并保持文本居中。有什么想法可以实现这一点吗?

我的可组合项:

  @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)
      }
    }
  }
Run Code Online (Sandbox Code Playgroud)

现在看起来是这样的: 在此输入图像描述

Sin*_*tem 3

如果您需要全角按钮,请用 包裹内容,然后将和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)
                )
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

否则您可以创建自定义布局

@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)
                    }
                }
            )
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这很好,但在文本很大的情况下,它会与图标重叠。有没有办法确保文本在整个按钮宽度内居中,但仍然受到限制,使其不与图标重叠? (2认同)