google-developer-training / basic-android-kotlin-compose-training-practice-problems

Apache License 2.0
96 stars 115 forks source link

Text not in the center of the box in compose quadrant #9

Open plugie opened 1 year ago

plugie commented 1 year ago

This is final result. The text is fill the box, not in the center.

Screenshot_1692890024

entropia9 commented 1 year ago

Hi, I had similar issue, turned out I wrote modifier instead of Modifier in first Text in ComposableInfoCard. Because of that modifier.weight(1f) was passed to the Text, which resulted in text filling the box.

plugie commented 1 year ago

Yes, you right.

I put

Text(
            text = title,
            modifier = modifier.padding(bottom = 16.dp),
            fontWeight = FontWeight.Bold
        )

in ComposableInfoCard

It should be

Text(
            text = title,
            modifier = Modifier.padding(bottom = 16.dp),
            fontWeight = FontWeight.Bold
        )

with capital M.

Then I become not understand.

When should we use Modifier and when should we use modifier ?

entropia9 commented 1 year ago

It depends on what you're trying to achieve. Think of it as any other parameter/argument. In this specific case, modifier that you pass in the function is supposed to be used as Column modifier.

private fun ComposableInfoCard(
// I'm omitting not important parts
   modifier: Modifier = Modifier  <--- this
) {
    Column(
        modifier = modifier   <--- goes here
            .fillMaxSize()
            .background(backgroundColor)
            .padding(16.dp),
// ...
    ) {
        Text(
            text = title,
            modifier = Modifier.padding(bottom = 16.dp), <--- completely unrelated text modifier 
            fontWeight = FontWeight.Bold
        )
//...
    }
}

When this Composable is called with Modifier.weight(1f), it translates to:

    Column(
        modifier = Modifier
            .weight(1f)
            .fillMaxSize()
            .background(backgroundColor)
            .padding(16.dp),
// ...
    ) {
        Text(
            text = title,
            modifier = Modifier.padding(bottom = 16.dp),
            fontWeight = FontWeight.Bold
        )
//...
    }

When you make a mistake and put modifier.padding(bottom=16.dp) instead of Modifier.padding(bottom=16.dp), it changes to this:

        Text(
            text = title,
            modifier = Modifier
                             .weight(1f)
                             .padding(bottom = 16.dp),
            fontWeight = FontWeight.Bold
        )