How to center item inside the surface in 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)
}
}
}
In image the circular black color shape is Surface and Go is Text inside Surface. I want to center the Go text inside the Surface. If I replace text with icon it center perfectly
Thanks in advance
for this we have align our Text composable to the centre, and we can't use align modifier inside Surface. so we will wrap our CommonText around Box and make a little change to CommonText that accept modifier.
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
)
}
}
....
Modified CommonText
as i don't know how CommonText Composable is created i assume it like following and make changes according to it.
@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
)
}
}
....