我正在尝试在 MainActivity.kt 中使用 kotlin 创建新的 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
}
关于android - 当我尝试动态创建 LinearLayout 时,无法重新分配 Val,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74429222/