[FIXED] Jetpack Compose – Order of Modifiers

Issue

Documentation says that Modifiers are applied from the left.
But from this example it looks like they are applied from the right:
First border and then padding because there is no space between text and border

Text("Hi there!", Modifier.padding(10.dp).border(2.dp, Color.Magenta))

enter image description here

Solution

  • In Android Compose resulting Image is being constructed from the outside layer toward the Composable in the center.
    This means that first defined Green border is outer border and the last defined Red border is inner border .
    This is very confusing since Green Modifier that is closest to Text Composable in the Code is furthest from it in the result.
  • This is in contrast to SwiftUI where Modifiers appear in the same order both in the Code and in the resulting Image.
    Modifier that is closest to the Composable in the Code is also closest to it in the resulting Image.
  • If you want to imagine that resulting Image is being constructed from the center where your Composable is positioned (like in SwiftUI) then Modifiers are applied in the opposite order from which they are given (from the bottom upward).
  • So if you have Text Composable with two border Modifiers
    • border Modifier that is furthest away from the Text Composable in the Code (the bottom Red one)
    • will be closest to the Text Composable in the resulting Image
  • Modifiers are applied from outer toward inner layer
    • Applying .border(2.dp, Color.Green) to the outmost layer
    • Applying .padding(50.dp) going inward
    • Applying .border(2.dp, Color.Red) to the innermost layer
package com.example.myapplication

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.foundation.*
import androidx.compose.foundation.layout.padding
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.setContent
import androidx.compose.ui.unit.dp

class MainActivity : AppCompatActivity() {
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContent {
      Text("Hi there!",
        Modifier
          .border(2.dp, Color.Green)
          .padding(50.dp)
          .border(2.dp, Color.Red)
      )
    }
  }
}

enter image description here

Answered By – ivoronline

Answer Checked By – Katrina (FixeMe Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *