android - 当我尝试动态创建 LinearLayout 时,无法重新分配 Val

标签 android xml kotlin dynamic val

我正在尝试在 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/

相关文章:

android在卸载应用程序后保留数据库

android - 后退按钮将应用程序返回到不一致状态

xml - 将 XML 馈送到 Google 日历

java - XStream 单个集合中的多种节点类型

kotlin - 如何在 Kotlin PSI 中获得类的完全限定域名?

spring-boot - 为什么我的Spring Boot应用程序不在 mustache 模板中呈现messages.properties

Android EditText 右对齐无法正常工作

android - 在 Cordova 点击文本框后显示顶部和底部菜单

Android - 拉解析器

android - 如何在 Kotlin 中将 if 表达式转换为 when