textState = te" /> textState = te" /> textState = te"/>

Are words and space characters in a Text composable treated as separate Text objects?

54 Views Asked by At

Here is the code:


@Composable
fun MainScreen() {

    var textState by remember { mutableStateOf("") }
    val onTextChange = { text : String ->
        textState = text
    }
    Column(Modifier.width(200.dp).padding(5.dp)) {
        Column(modifier = Modifier.width(intrinsicSize = IntrinsicSize.Min)) {
            Text(
                modifier = Modifier
                    .padding(start = 4.dp),
                text = textState
            )
            Box(Modifier.height(10.dp).fillMaxWidth().background(Color.Blue))
        }
        MyTextField(text = textState, onTextChange = onTextChange)
    }

}


@Composable
fun MyTextField(text: String, onTextChange : (String) -> Unit) {
    TextField(
        value = text,
        onValueChange = onTextChange
    )
}

When I enter this line of text: This is

It appears in the Text composable like this:


    This 
    is

To me, it looks as if each time I hit the space bar to start a new word, I have just created a new Text object. I guess the code works like this: The first letter is "T", what is the min value? It takes one character: 1.dp. Ok, recompose the Text composable and so on .. until I hit the space bar. At this time the word This is treated as a whole new Text because when I enter is, this word is on a new line. In short, it looks like I have changed the code to :

 Text("This")
 Text("is")

My question is

  1. Is the 'Text' composable treated as a special case as the instrinsic measurements apply to the words it contains?
  2. Is the space bar a magic device to "create" Text composables?

Thank you for reading.

1

There are 1 best solutions below

5
Gabriele Mariotti On

In your case you should use IntrinsicSize.Max

Column(
    modifier = Modifier.width(intrinsicSize = IntrinsicSize.Max)
) {
    Text()
    Box(Modifier.fillMaxWidth())
}

enter image description here

Using IntrinsicSize.Min in your code the internal MinIntrinsicWidthModifier calculates child's minIntrinsicWidth = the minimum width that the layout can be such that the content of the layout will be painted correctly, and it means having the width = longest word width in the Text.

enter image description here