2

I'm trying to create new LinearLayout with kotlin inside MainActivity.kt

for (i in 0 until tileArr.size){
    var tileLayout: LinearLayout = LinearLayout(this)
    tileLayout.marginBottom = 10
}

while it throws error Val cannot be reassigned on line: tileLayout.marginBottom = 10

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Nika Jobava
  • 113
  • 3
  • 10

1 Answers1

2

You cannot modify those properties directly, you need to use LayoutParams.

 for (i in 0 until tileArr.size){
        var tileLayout: ViewGroup = LinearLayout(this)
        val params = <Parent ViewGroup Type>.LayoutParams( // if the parent is FrameLayout, this should be FrameLayout.LayoutParams
            LinearLayout.LayoutParams.WRAP_CONTENT, // modify this if its not wrap_content
            LinearLayout.LayoutParams.WRAP_CONTENT // modify this if its not wrap_content
        )
        params.setMargins(0, 0, 0, 10) // last argument here is the bottom margin
        tileLayout.layoutParams = params
  }
z.g.y
  • 5,512
  • 4
  • 10
  • 36
  • 1
    Also important, the type of LayoutParams that you create should match the type of the **parent** ViewGroup for this view. – Tenfour04 Nov 14 '22 at 13:58