Search code examples
androidandroid-jetpack-composeandroid-compose-textfieldandroid-jetpack-compose-row

Jetpack Compose: how to place text on the right side of the row?


I'm trying to place two texts inside a Row, one nailed to the left edge, the other to the right. Moreover, if the left text is too long, it should not overlap the right text, but should be wrapped on a new line. The problem is that both the right and left texts are optional. If, for example, there is no left text, I need the right text to be located on the line at the right edge.

Here's an example of what it should look likeenter image description here

Here is my code:

   Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(top = 4.dp),
                    horizontalArrangement = Arrangement.SpaceBetween,
                    verticalAlignment = Alignment.CenterVertically,
                ) {
                    if (hasLeft()) {
                        Text(
                            modifier = Modifier.weight(1f),
                            text = leftText,                            
                        )
                    }

                    if (hasRight()) {
                        Text(
                            modifier = Modifier.padding(start = 4.dp),
                            text = rightText,                                
                        )
                    }
                }

As a result, when the no left text, the right text is located on the left side, but I need it to be on the right, how to fix this?

Please, help me.


Solution

  • Set fill property of Modifier.weight to false for the left Text and add a Spacer when left text is not available

    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(top = 4.dp),
        horizontalArrangement = Arrangement.SpaceBetween,
        verticalAlignment = Alignment.CenterVertically,
    ) {
        if (hasLeft) {
            Text(
                modifier = Modifier.weight(1f, fill = false),
                text = leftText,
            )
        }else {
            Spacer(Modifier.weight(1f))
        }
    
        if (hasRight) {
    
            Text(
                modifier = Modifier.padding(start = 4.dp),
                text = rightText
            )
        }
    }