首页 > 解决方案 > 在 tableRow Kotlin 中未正确创建按钮

问题描述

我正在尝试动态创建一个带有 Button 的 tableRow 视图。但是创建的 Button 的大小是 0dp 宽度和高度(正如我在 Layout Inspector 中看到的那样)

MainActivity.kt 代码:

    val tableRow = TableRow(this)
    tableRow.layoutParams = ConstraintLayout.LayoutParams(
            ConstraintLayout.LayoutParams.MATCH_PARENT,
            ConstraintLayout.LayoutParams.WRAP_CONTENT
    )     
    val button = Button(this)
    button.layoutParams = ConstraintLayout.LayoutParams(
        ConstraintLayout.LayoutParams.WRAP_CONTENT,
        ConstraintLayout.LayoutParams.WRAP_CONTENT
    )
    button.text = "Hello"
    tableRow.addView(button)
    deviceLayout.addView(tableRow)

活动主.xml:

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    ...
    ...
    <TableLayout
        android:id="@+id/deviceLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp"
        app:layout_constraintTop_toBottomOf="@+id/StatusString"
        tools:layout_editor_absoluteX="0dp" >
    </TableLayout>

</androidx.constraintlayout.widget.ConstraintLayout>```

标签: androidkotlin

解决方案


推荐阅读