Android. How to correctly position elements in row?

50 Views Asked by At

I'm trying to position elements in my Row like this: text first, immediately followed by an icon, and a second icon that should be nailed to the end (right edge). Here is a visual example of what it should look like: enter image description here

And when text very long I need: enter image description here

Here is my code:

 Row(
        modifier = Modifier
            .fillMaxWidth(),
        horizontalArrangement = Arrangement.SpaceBetween,
    ) {
        Row(modifier = Modifier.weight(1f)) {
            Text(
                text,
                modifier = Modifier
                    .align(Alignment.Top)
            )

                Icon(
                    modifier = Modifier.padding(start = 12.dp),
                    painter = painterResource(R.drawable.ic_circle),
                    contentDescription = ""
                )
        }

        Box(
            modifier = Modifier
                .size(26.dp)
                .align(Alignment.CenterVertically),
        ) {
            Image(
                modifier = Modifier.align(Alignment.Center),
                painter = painterResource(R.drawable.ic_square),
                contentDescription = null,
            )
        }
    }

The problem is that the text can be very long, in which case my first icon (circle) is not displayed. Please help, how can I fix this?

1

There are 1 best solutions below

0
On

You can use Modifier.weight(1f, fill = false) on Text so Image is always measured with its own width while text keeps growing. Row and Column measures Composables without Modifier.weight first then divides space between the ones with Modifier.weight.

Text(
    text,
    modifier = Modifier
        .align(Alignment.Top)
        .weight(1f, fill = false)
)

And it can be tested like this

@Preview
@Composable
private fun RowTest() {
    var text by remember {
        mutableStateOf("Text text")
    }

    Column {
        SampleComposable(text = text)
        TextField(value = text, onValueChange = { text = it })
    }
}

@Composable
private fun SampleComposable(text: String) {
    Row(
        modifier = Modifier
            .fillMaxWidth(),
        horizontalArrangement = Arrangement.SpaceBetween,
    ) {
        Row(modifier = Modifier.weight(1f)) {
Text(
    text,
    modifier = Modifier
        .align(Alignment.Top)
        .weight(1f, fill = false)
)

            Icon(
                modifier = Modifier.padding(start = 12.dp),
                imageVector = Icons.Default.Circle,
                contentDescription = ""
            )
        }

        Box(
            modifier = Modifier
                .size(26.dp)
                .align(Alignment.Top),
        ) {
            Image(
                modifier = Modifier.align(Alignment.Center),
                imageVector = Icons.Default.Square,
                contentDescription = null,
            )
        }
    }
}