Home > database >  How to put Text composables in Row, one with a mutable width
How to put Text composables in Row, one with a mutable width

Time:08-20

I want to know the way to put Text composables in Row, one with a mutable width for a TopAppBar.

Regarding the two Texts, one has a width that varies with the number of characters, and the other has a fixed number of characters and we want the string to be displayed reliably.

I tried writing codes to make that, but it did not work as I had expected.

Here is my codes and a image of what I thought.

@Composable
fun AppBarTestScreen() {

    Column {

            TopAppBar(
                title = {
                    Row(Modifier.fillMaxWidth()) {
                        
                        Text(
                            text = "〇〇〇〇〇〇",
                            modifier = Modifier.wrapContentWidth().widthIn(max = 210.dp),
                            maxLines = 1,
                            overflow = TextOverflow.Ellipsis,
                            softWrap = false
                        )

                        Text(
                            text = "'s Attribute",
                            modifier = Modifier.fillMaxWidth().clipToBounds(),
                            textAlign = TextAlign.Start,
                            overflow = TextOverflow.Clip,
                            softWrap = false
                        )

                    }
                }
            )

            ....

    }

}

enter image description here

I tried a variety of Modifier functions and patterns

For now, I set a maximum width on the first Text. However, this works well when the device is in portrait orientation, but not in landscape orientation. Furthermore, the results are not clear when it comes to tablets and other devices.

If there is no other way, I will eventually have to rely on unstable external libraries, but is there any way to make what I want without them?

CodePudding user response:

Apply the weight modifier to the 1st Text:

Row(Modifier.fillMaxWidth()) {

    Text(
        text = "〇〇〇〇〇〇〇〇〇〇〇〇〇〇〇〇",
        modifier = Modifier.weight(1f),
        maxLines = 1,
        overflow = TextOverflow.Ellipsis,
    )

    Text(text = "'s Attribute")
}

enter image description here

If you want to avoid to fill the whole space with the 1st Text use Modifier.weight(1f,false):

Text(
    text = "〇〇〇〇〇〇〇",
    modifier = Modifier.weight(1f,false),
    maxLines = 1,
    overflow = TextOverflow.Ellipsis,
)

enter image description here

  • Related