我在做什么:尝试使用 onGlobalLayout() 中的
的 setColumnCount()
更改 GridLayout
的列数OnGlobalLayoutListener()
我想达到什么目的:我想在确定多少之后更改 GridLayout
的列数屏幕尺寸留给它的子元素,即如果屏幕尺寸只能容纳 5 个 GridLayout 的
子元素,那么我会将列数设置为 5,这样在第 5 个元素之后,第 6 个元素将被放置在第 2 个行等。
我如何尝试实现此目的:首先我得到 GridLayout
的总宽度使用 ViewTreeObserver
。然后将其除以单个子元素的大小,然后将其设置为 setColumnCount()
值。
代码:
ViewTreeObserver vto = gridLayout.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
gridLayout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
int gridLayoutWidth = Utils.pxToDp(mContext,gridLayout.getWidth()); //GridLayout width in DP
int childElementWidth = 44; //Child element width in DP
int columnCount = (gridLayoutWidth/childElementWidth);
gridLayout.setColumnCount(columnCount);
}
});
我卡在什么地方了 columnCount 必须大于或等于每个子节点的 LayoutParams 中定义的所有网格索引(和跨度)的最大值
最佳答案
在使用减少的列数或行数更新之前,需要在 GridLayout 的新范围内设置 subview 的列或行规范。
我在 Kotlin 中创建了一个函数来为我执行此操作,并在布局中使用指定的列数和固定数量的 subview 。很抱歉没有用 Java 编写它,但这并没有什么不同。
fun setGridColumns(gridLayout: GridLayout, columns: Int) {
var col = 0
var row = 0
for (child in gridLayout.children) {
val params = child.layoutParams as GridLayout.LayoutParams
params.columnSpec = GridLayout.spec(col, 1, 1f)
params.rowSpec = GridLayout.spec(row, 1, 1f)
if (col + 1 == columns) {
col = 0
row++
} else {
col++
}
}
gridLayout.requestLayout() // Forces maxIndex to be recalculated when columnCount is set
gridLayout.columnCount = columns
}
关于android - columnCount 必须大于或等于每个子项的 LayoutParams 中定义的所有网格索引(和跨度)的最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38805731/