如何在jetpack compose中将Surface中的项目居中

Sum*_*nan 8 android center surface android-jetpack-compose

如何在jet pack 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)
        }
    }
}


Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

在图像中,圆形黑色形状是 Surface,Go 是 Surface 内的文本。我想将 Go 文本置于 Surface 的中心。如果我用图标替换文本,它会完美居中

提前致谢

Bha*_*vin 7

为此,我们将可组合文本对齐到中心,并且不能在 Surface 内使用对齐修饰符。因此,我们将把 CommonText 包裹在 Box 周围,并对接受修饰符的 CommonText 进行一些更改。

带图标中心的圆形

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

修改后的通用文本

因为我不知道 CommonText Composable 是如何创建的,所以我假设它类似于以下内容并根据它进行更改。

@Composable
fun CommonText(modifier: Modifier = Modifier, .... ) {
    Text(modifier = modifier, .... )
}
Run Code Online (Sandbox Code Playgroud)

编辑 - 更简单的版本

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