Setting rowcount and column count for grid layout dynamically

烂漫一生 提交于 2019-12-12 14:14:15

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!