Val cannot be reassigned while I try to create LinearLayout dynamically

171 views Asked by At

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

1

There are 1 answers

1
z.g.y On

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
  }