androidandroid-jetpack-compose

How to force a second line in two texts that are displayed in the left and right margin when the first text is too large?


Row {
        Text(
            modifier = Modifier
                .weight(1f)
                .padding(top = 16.dp, bottom = 8.dp),
            text = first.toAnnotatedString(),
            style = style
        )
        Text(
            modifier = Modifier.padding(top = 16.dp, bottom = 8.dp),
            text = second.toAnnotatedString(),
            style = style
        )
    }

I am using the following code to make two texts display, one aligned to the right margin and the other aligned to the left margin:

When the font size is small, the content is displayed as expected, as seen in the image (green box):

enter image description here

But when you change the font size, the text on the left looks horrible:

enter image description here

How could I make it so that when the text is too large, the content on the left is displayed on a single line and the content on the right is displayed on another line?


Solution

  • A row is expanding only on the horizontal axis, so if you want to put more than one line in a single row, it can't succeed. You can use a FlowRow composable that helps to have more than one line, like this:

    @OptIn(ExperimentalLayoutApi::class)
    @Composable
    fun ExpandableText(modifier: Modifier = Modifier) {
        FlowRow(
            modifier = modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween
        ) {
            Text(
                modifier = Modifier.padding(top = 16.dp, bottom = 8.dp),
                text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed non risus.",
                style = MaterialTheme.typography.bodyLarge,
                overflow = TextOverflow.Ellipsis,
                maxLines = 1
            )
    
            Text(
                modifier = Modifier.padding(top = 16.dp, bottom = 8.dp),
                text = "Show more",
                style = MaterialTheme.typography.bodyLarge,
            )
        }
    }
    

    Result Image for multiple lines:

    @OptIn(ExperimentalLayoutApi::class)
    @Composable
    fun ExpandableText(modifier: Modifier = Modifier) {
        FlowRow(
            modifier = modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween
        ) {
            Text(
                modifier = Modifier
                    .padding(top = 16.dp, bottom = 8.dp),
                text = "Lorem ipsum ",
                style = MaterialTheme.typography.bodyLarge,
                overflow = TextOverflow.Ellipsis,
                maxLines = 1
            )
    
            Text(
                modifier = Modifier
    
                    .padding(top = 16.dp, bottom = 8.dp),
                text = "Show more",
                style = MaterialTheme.typography.bodyLarge,
            )
        }
    }
    

    Result: