Search code examples
android-layoutuser-interfacerowandroid-jetpack-compose

Android compose: how to position icons in the margins of a text in a row?


I would like to have a card with the following layout:

  • an icon on the left;
  • text in the center;
  • an icon to the right;

The icons must always be present regardless of the length of the text: enter image description here

In this regard I wrote the following code:

fun test() {
Card(
    modifier = Modifier.fillMaxWidth(),
    shape = RoundedCornerShape(16.dp)
) {
    Row(
        Modifier.fillMaxWidth().padding(all = 16.dp),
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.SpaceBetween
    ) {
        Icon(imageVector = Icons.Default.ArrowBack, contentDescription = "Back")
        Text("Title", textAlign = TextAlign.Center)
        Icon(imageVector = Icons.Default.Delete, contentDescription = "Delete")
    }
}

}

The problem is that if the text is too long, then the last icon "disappears": enter image description here

A solution could be to use Modifier.width (x.dp) on the text, but in this case how do I set the value of x to cover the maximum possible width within the icons?


Solution

  • You can apply Modifier.weight(1f) to the Text composable.

    Something like:

    Row(
        Modifier
            .fillMaxWidth()
            .height(30.dp)
    ){
        Icon(imageVector = Icons.Default.ArrowBack, contentDescription = "Back")
        Text("Title", textAlign = TextAlign.Center,
            modifier = Modifier.weight(1f)) // Fill this with remaining space available
        Icon(imageVector = Icons.Default.Delete, contentDescription = "Delete")
    }
    

    enter image description here