我正在LinearLayouts动态添加GridLayout。我正在寻找它们以显示为网格视图。
是否可以计算一行中可以放置多少个线性布局并为网格布局设置列数?
我应该使用 gridview 自动对齐它们吗?
3824 次
2 回答
3
如果要根据 的宽度计算列数GridLayout,请覆盖该onMeasure方法。它提供widthSpec和heightSpec作为参数,您可以使用MeasureSpec.getSize()从中获取以像素为单位的实际宽度和高度。GridLayout从那里,根据您刚刚找到的宽度计算您想要显示的列数,并使用setColumnCount它来显示该列数。
于 2013-04-17T14:38:25.053 回答
0
GridLayout 的覆盖onMeasure工作。示例(在 Kotlin 中,但应该很容易翻译成 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)
}
requestLayout()尽管@drdaanger 在他的回复中提到了什么,但我不必这样做。
于 2019-08-02T15:43:58.530 回答