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

Time:07-22

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?

CodePudding user response:

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

CodePudding user response:

You can make this spacing arrangement with distributed weights directly. I've added each icon weight 1 and rest of the space to title. Or you may also use ConstraintLayout for this, but row with weights works fine too.

Row(
    Modifier.fillMaxWidth().padding(16.dp),
    verticalAlignment = Alignment.CenterVertically,
    horizontalArrangement = Arrangement.SpaceBetween
) {
    Icon(
        modifier = Modifier.weight(1f),
        imageVector = Icons.Default.ArrowBack, contentDescription = "Back"
    )
    Text(
        modifier = Modifier.weight(8f),
        text = "Title",
        textAlign = TextAlign.Center
    )
    Icon(
        modifier = Modifier.weight(1f),
        imageVector = Icons.Default.Delete,
        contentDescription = "Delete"
    )
}
  • Related