10x10 table 未正确创建

10x10 table is not creating properly

我想创建 10x10 网格,所以我使用 TableLayout and this answer

我正在像这样以编程方式创建我的 table视图:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val table = TableLayout(this)
    for (i in 0..9) {
        val row = TableRow(this)
        for (j in 0..9) {
            val cell = EditText(this)
            cell.setText("test")
            row.addView(cell)
        }
        table.addView(row)
    }

    setContentView(table)
}

问题: 这会起作用,但会替换此 activity 的布局(可能是因为我正在调用 setContentView(table)

如何将我的 table 视图放在 TableLayout 中(它是 activity 布局中的视图)而不是我当前的结果?


为了更好地理解,我当前的代码给出了这个结果(正如我上面提到的):

您应该先检查 Android basics

总之。将您的 TableLayout 放入您的布局中,使用 findViewById() 并使用它而不是创建一个新布局。

val table = findViewById<TableLayout>(R.id.tablelayout)
for (i in 0..9) {
 // ... Same code
}