【问题标题】:Setting rowcount and column count for grid layout dynamically动态设置网格布局的行数和列数
【发布时间】:2013-04-17 14:25:18
【问题描述】:

我正在动态地将LinearLayouts 添加到GridLayout。我希望它们显示为网格视图。
是否可以计算一行可以放置多少个线性布局并设置网格布局的列数?
我应该使用 gridview 自动对齐它们吗?

【问题讨论】:

    标签: android android-widget


    【解决方案1】:

    如果要根据GridLayout 的宽度计算列数,请覆盖onMeasure 方法。它提供widthSpecheightSpec 作为参数,您可以使用MeasureSpec.getSize() 从中获取以像素为单位的实际宽度和高度。从那里,根据您刚刚找到的GridLayout 的宽度计算您要显示的列数,并使用setColumnCount 使其显示该列数。

    【讨论】:

    • 有点晚了,我知道,但事情没有这么简单。您还需要重新计算或使每个子视图的布局参数的行和列规范无效,并在调用setColumnCount(int) 之前调用requestLayout()。不这样做通常会导致 IllegalArgumentException。
    【解决方案2】:

    覆盖 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)
    }
    

    尽管@drdaanger 在他的回复中提到了什么,但我不必requestLayout()

    【讨论】:

      猜你喜欢
      • 2018-11-30
      • 2019-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-15
      • 2018-07-14
      • 2019-03-01
      相关资源
      最近更新 更多