Search code examples
androidkotlinandroid-jetpack-composeandroid-jetpack-compose-material3

How to use offset for start and end in Jetpack Compose?


I have a row that contains a text, an icon and a text:

Row {
    Text(text = "I")
    Icon(
        imageVector = Icons.Default.Favorite,
        contentDescription = null,
    )
    Text(text = "you")
}

I need to write "I ❤️ you". What I need is to cut the space from the start and the end of the icon to look like this "I❤️you". So I tried to use an offset:

Row {
    Text(text = "I")
    Icon(
        modifier = Modifier.offset(
            x = (-12).dp
        ),
        imageVector = Icons.Default.Favorite,
        contentDescription = null,
    )
    Text(text = "you")
}

But I only could cut 12 dp from the beginning. How to cut as well from the end?


Solution

  • Using offset you won't be able to change size of item or remove it's padding – "cut the space". Offset is just placing item depending on provided value (in your case in X axis by -12dp). So it's not the best Modifier for your purposes.

    However, it could be achieved using offset, take a look at this:

    Row {
        Text(text = "I")
        Icon(
            modifier = Modifier.offset(x = (-2).dp),
            imageVector = Icons.Default.Favorite,
            contentDescription = null,
        )
        Text(
            modifier = Modifier.offset(x = (-4).dp),
            text = "you",
        )
    }
    

    First we offset the icon to the left to align with the Text "I", then we offset the Text "you" to align with a heart.

    Like you can see it could be done using offset but I would suggest to experiment with other modifiers, I think that it could be achieved in simpler way.

    You could also just use the simplest solution and use heart in Text, like this:

    Text(text = "I❤️you")
    

    It's possible to use emoji in Text.