问题
I am adding linearlayouts to GridLayout dynamically. I want that to be displayed like grid view. Is it possible to calculate how many linear layouts can be placed in one row and set column count for grid layout or i should use gridview to align them automatically.
回答1:
If you want to calculate the column count based on the width of the GridLayout
, override the onMeasure
method. It provides widthSpec
and heightSpec
as parameters, from which you can get the actual width and height in pixels using MeasureSpec.getSize(). From there, calculate how many columns you'd like to show based on the width of the GridLayout
you just found, and use setColumnCount
to make it display that number of columns.
回答2:
Override onMeasure
of the GridLayout works. Example (in Kotlin, but should be easily translated to Java):
override fun onMeasure(widthSpec: Int, heightSpec: Int) {
var childWidth = 0
for (i in 0 until childCount) {
val c = getChildAt(i)
if (c.visibility == View.GONE) {
continue
}
val params = c.layoutParams
if (params.width>childWidth) childWidth = params.width
}
val width = MeasureSpec.getSize(widthSpec)
columnCount=width/childWidth
super.onMeasure(widthSpec, heightSpec)
}
I didn't have to requestLayout()
despite what @drdaanger mentions in his reply.
来源:https://stackoverflow.com/questions/16062675/setting-rowcount-and-column-count-for-grid-layout-dynamically