android gridlayout 行和列与结果不匹配

android gridlayout row and column not match the result

我想创建一个GridLayout

这是我的服务器设置:

 items.add(listOf(4, 3, 0, 0)) -> start at x: 0 - y:0 expand horizontal : 4, vertical 3
 items.add(listOf(1, 1, 0, 3)) -> start at x: 0 - y:3 expand horizontal : 1, vertical 1
 items.add(listOf(1, 1, 1, 3)) -> start at x: 1 - y:3 expand horizontal : 1, vertical 1
 items.add(listOf(1, 1, 2, 3)) -> start at x: 2 - y:3 expand horizontal : 1, vertical 1
 items.add(listOf(1, 1, 3, 3)) -> start at x: 3 - y:3 expand horizontal : 1, vertical 1           

这是我绘制 table:

的代码
private fun populateTable(){
        val items = AppUtil.getListItemsForGroupLayout(layoutCode)
        val totalRows = AppUtil.getRowOrColumns(layoutCode) -> 4 rows
        val totalCols = AppUtil.getRowOrColumns(layoutCode) -> 4 columns

        tableView.columnCount = totalCols
        tableView.rowCount = totalRows

        items.forEach {
            val params = GridLayout.LayoutParams()
            params.width = 0
            params.height = 0

            params.rowSpec = GridLayout.spec(it[3], it[1].toFloat())
            params.columnSpec = GridLayout.spec(it[2], it[0].toFloat())

            val view = TextView(this@CallScreen)
            view.text = "${it[3]} - ${it[2]} - ${it[1]} - ${it[0]}"
            view.setBackgroundColor(Int.randomColor())
            view.layoutParams = params
            tableView.addView(view)
        }
    }

但结果不一样:

谁能帮我解决这个问题?谢谢

我不认为这两行符合您的要求:

   params.rowSpec = GridLayout.spec(it[3], it[1].toFloat())
   params.columnSpec = GridLayout.spec(it[2], it[0].toFloat())

根据您的评论,it[0] 包含 colspanit[1] 包含 rowspan,但在转换后到 float,调用重载 spec(int start, float weight),它将 weight factor 作为第二个参数,大小(colspan 或 rowspan)为 1。

也许重载spec(int start, int size, float weight)会更合适:

   params.rowSpec = GridLayout.spec(it[3], it[1], it[1].toFloat())
   params.columnSpec = GridLayout.spec(it[2], it[0], it[0].toFloat())
   params.rowSpec = GridLayout.spec(it[3], it[1].toFloat())
   params.columnSpec = GridLayout.spec(it[2], it[0].toFloat())

您在这里使用的 this version 仅提供起始值和权重值。

查看 other overloaded versions of GridLayout.spec, there is another parameter (size) that also controls this behavior as by looking into the GridLayout source code,所有这些重载方法都调用私有构造函数:

    private Spec(boolean startDefined, int start, int size, Alignment alignment, float weight) {
        this(startDefined, new Interval(start, start + size), alignment, weight);
    }

解法:

要解决此问题,我们需要通过在 params.columnSpec:

中使用 this overloaded version 来使用 size 参数

因此,在您的代码中替换:

params.columnSpec = GridLayout.spec(it[2], it[0].toFloat())

与:

params.columnSpec = GridLayout.spec(it[2], it[0], 1f)

预览: