I need to show a 4x10 grid of random colors. The grid should fill the screen horizontally and vertically, and all cells should be of equal dimensions. Since the grid (4x10) dimensions can change in the future, GridLayout made more sense to me than TableLayout. GridView and RecyclerView are out because I don't need any scrolling behavior.
Since I need to add these child views at runtime, I started with calculating cell width and height as a ration of screen width and height. Then I stumbled across this SO post which says GridLayout has better ways to achieve such behavior. There is a code example for static (XML) based views, but I am not able to find a Java/Kotlin example. I am experimenting with GridLayout.Spec to use in the LayoutParams for the child views, but can't figure out how it works.
Updated with a screenshot of desired layout. This image is 12x10, but I want the flexibility to change the dimensions (compile time).

Similar to LinearLayout, there is a weight attribute in GridLayout spec - which you can set to 1 for all views. Similar to LinearLayout, make the width and height 0 using weights. Use Undefined as position as you want to draw the views in sequence, else pass the corresponding position for each cell.
gridLayout.rowCount = rowCount
gridLayout.columnCount = colCount
for (i in 1..rowCount*colCount){
val layoutParams: GridLayout.LayoutParams = GridLayout.LayoutParams(
GridLayout.spec(GridLayout.UNDEFINED, 1f),
GridLayout.spec(GridLayout.UNDEFINED, 1f)).apply {
width = 0
height = 0
}
val blueView = View(this).apply {
setBackgroundColor(Color.BLUE)
}
gridLayout.addView(blueView, layoutParams)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With