Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Jetpack Compose Trying to Align a Text inside a Box

I created a Box containing an Image and Text. With Box contentAlignment set to TopStart, the Text is not aligning properly with the Image. Horizontally, things look ok, but there is unexpected vertical padding (even after setting it 0).

Similarly, BottomStart alignment sets the Text a few pixels higher than the Image.

Box(contentAlignment = Alignment.TopStart,) {
    Image(painter = painterResource(id = R.drawable.ic_launcher_background), contentDescription = "",
        modifier = Modifier.size(125.dp),
        colorFilter = ColorFilter.tint(MaterialTheme.colors.onBackground)
    )

    Text(text = "4",
        color = MaterialTheme.colors.primary,
        fontSize = 44.sp,
        textAlign = TextAlign.Center
    )
}

Box-Preview

like image 765
Faysal Ahmet Avatar asked Sep 01 '25 02:09

Faysal Ahmet


2 Answers

You can check according to here:

@Composable
fun MainScreen() {
.
.
   Box(modifier = Modifier.size(height = 90.dp, width = 290.dp)) {
    Text("TopStart", Modifier.align(Alignment.TopStart))
    Text("TopCenter", Modifier.align(Alignment.TopCenter))
    Text("TopEnd", Modifier.align(Alignment.TopEnd))

    Text("CenterStart", Modifier.align(Alignment.CenterStart))
    Text("Center", Modifier.align(Alignment.Center))
    Text(text = "CenterEnd", Modifier.align(Alignment.CenterEnd))

    Text("BottomStart", Modifier.align(Alignment.BottomStart))
    Text("BottomCenter", Modifier.align(Alignment.BottomCenter))
    Text("BottomEnd", Modifier.align(Alignment.BottomEnd))
   }
}

enter image description here

like image 159
DevPolarBear Avatar answered Sep 02 '25 15:09

DevPolarBear


You need to use the .align() modifier on your Text inside the Box to center/position it. e.g. Text(..., modifier = Modifier.align(Center), ..).

Alternatively, you can make your text fill up the entire Box (by adding .fillMaxSize() to it) and the use the textAlign property.

like image 28
Adib Faramarzi Avatar answered Sep 02 '25 17:09

Adib Faramarzi