如何在Jetpack Compose中将Item居中于Surface中

6
如何在Jetpack Compose中将项目居中在表面内
@Composable
fun RoundedShapeWithIconCenter(
    modifier: Modifier = Modifier,
    parentSize : Dp,
    parentBackgroundColor : Color,
    childPadding : Dp,
    icon : Painter,
    iconSize : Dp,
    iconTint : Color,
    elevation : Dp = 0.dp,
    isTextOrIcon : Boolean = false,
    insideText : String = "",
    insideTextColor : Color = colorResource(id = R.color.black),
    fontSize: TextUnit = 16.sp
) {
    Surface(
        modifier = modifier.size(parentSize),
        shape = RoundedCornerShape(50),
        color = parentBackgroundColor,
        elevation = elevation,
    ) {
        if (isTextOrIcon) {
            CommonText(value = insideText, fontSize = fontSize, color = insideTextColor, textAlign = TextAlign.Center)
        } else {
            Icon(painter = icon, contentDescription = "Back Arrow", modifier = Modifier
                .size(iconSize)
                .padding(childPadding), tint = iconTint)
        }
    }
}


enter image description here

在图片中,圆形黑色形状是 Surface,Go 是 Surface 内部的文本。我想将 Go 文本居中在 Surface 中。如果我用图标替换文本,则可以完美居中。
提前感谢。

你能分享一下CommonText组合函数吗?因为我对它有点困惑。 - Bhavin
fun CommonText(value : String, fontSize : TextUnit, color : Color, modifier : Modifier = Modifier, fontWeight : FontWeight = FontWeight.Normal, textAlign: TextAlign = TextAlign.Left) { Text(text = value, fontSize = fontSize, color = color, modifier = modifier) } - Suman Radhakrishnan
谢谢,我已经添加了一个更简单的版本,不需要将修饰符添加到文本中,因为Box还提供了contentAlignment参数。 - Bhavin
1个回答

6

因此,我们需要将文本组件居中对齐,并且无法在 Surface 中使用 align 修饰符。因此,我们将在 Box 中包装 CommonText,并对其进行一些修改以接受修饰符。

RoundedShapeWithIconCenter

....
if (isTextOrIcon) {
    Box(modifier = Modifier
        .fillMaxSize(1.0f) // it will fill parent box
        .padding(8.dp)) { // padding will help us to give some margin between our text and parent if text greater then our parent size

            CommonText(
                value = insideText, 
                fontSize = fontSize, 
                color = insideTextColor,
                modifier = Modifier.align(Alignment.Center) // this will help it to align it to box center
            )
        }
}
....

修改后的 CommonText

由于我不知道 CommonText 可组合对象是如何创建的,因此我假设它的创建方式如下,并根据此进行更改。

@Composable
fun CommonText(modifier: Modifier = Modifier, .... ) {
    Text(modifier = modifier, .... )
}

编辑 - 更简单的版本

....
if (isTextOrIcon) {
    Box(modifier = Modifier
        .fillMaxSize(1.0f) // it will fill parent box
        .padding(8.dp),// padding will help us to give some margin between our text and parent if text greater then our parent size
        contentAlignment = Center) { // contentAlignment will align its content as provided Alignment in our case it's Center

            CommonText(
                value = insideText, 
                fontSize = fontSize, 
                color = insideTextColor
            )
        }
}
....

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接