如何正确设置LayoutParams

塔米尔·阿布特布尔

我正在创建一个由10X10单元格组成的表格,它(在创建所有单元格之后)不适合其父级。

  • 为了使我在显示代码之前更容易理解,该表如下所示:

在此处输入图片说明

如您所见,每个表格单元格都是一个以“ Test”作为文本的按钮,我无法使此10X10网格展开以填充其父级(视图水平退出屏幕,而垂直填充)


我正在以编程方式创建每个单元格,如下所示:

    val table = findViewById<TableLayout>(R.id.table)
    for (i in 0..9) {    //10 rows inside the table
        val row = TableRow(this)
        for (j in 0..9) {    //10 cells inside every row

            val cell = Button(this)   
            cell.layoutParams =  TableRow.LayoutParams(

                TableRow.LayoutParams.WRAP_CONTENT,
                TableRow.LayoutParams.WRAP_CONTENT
            )

            cell.text = "test"
            cell.setTextColor(Color.RED)
            cell.setBackgroundColor(Color.WHITE)
            cell.setPadding(0, 0, 0, 0)
            row.addView(cell)
        }
        table.addView(row)
    }
  • 我的下一步是更改我layoutParams为每个单元格设置的方式,我试图更改每个单元格的尺寸,如下所示:

      cell.layoutParams =  TableRow.LayoutParams(
                 //table = the view that contains all cells
    
                 table.width/5,     //make the cell width = 20% of the parent width
                 table.height/10    //make the cell height= 10% of the parent height           
            ) 
    

For some reason, this made the whole table disappear and setting the layoutparams to MATCH_PARENT had the same effect as WRAP_CONTENT.


I have checked android - setting LayoutParams programmatically and LayoutParams but I haven't found the answer.

What am I doing wrong that makes my table disappear, and how can I make the cells fit to the table size?

Alex Cohn
  1. you write table.width/5 so you probably use j in 0..4

  2. See the reference for TableLayout:

    The children of a TableLayout cannot specify the layout_width attribute. Width is always MATCH_PARENT. However, the layout_height attribute can be defined.

    Use android:stretchColumns to have the table adjust the button widths correctly.

    But,

    The children of a TableRow do not need to specify the layout_width and layout_height attributes in the XML file. TableRow always enforces those values to be respectively ViewGroup.LayoutParams.MATCH_PARENT and ViewGroup.LayoutParams.WRAP_CONTENT.

    This means that, by the book, you cannot fill the parent with a table vertically. But by hook or by crook, you can force the height of each button to be exactly 1/10 of the full height.

    What you can't do, is take table.height while building your layout, because at this stage the height of the parent is not known yet. I hope you can calculate this height based on the screen size.

  3. With such programmatic setup, you don't need table layout, horizontal linear views inside vertical that fills the parent could be enough.

  4. 使用ConstraintLayout可以将元素的宽度和高度指定为父级的百分比,请参见https://android.jlelse.eu/whats-new-in-constraint-layout-1-1-0-acfe30cfc7be

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章