Val不能被重新分配,而我尝试动态创建线性布局



我试图在MainActivity.kt中创建新的LinearLayout

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

抛出错误Val不能重新赋值在线:tileLayout.marginBottom = 10

您不能直接修改这些属性,您需要使用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
}

相关内容

  • 没有找到相关文章

最新更新