android - columnCount 必须大于或等于每个子项的 LayoutParams 中定义的所有网格索引(和跨度)的最大值

标签 android android-gridlayout

我在做什么:尝试使用 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/

相关文章:

android - GridLayoutManager 中可变列数

Android:创建方形单元格表

android - 减少android中gridlayout的行/列数

android - 网格布局。如何设置列之间的空间?

android - 在 gridLayout 中从右到左放置项目

android - 在 Android Things 上扫描 Wifi 网络返回空列表

java - 从 MP3/MIDI 文件中提取音频数据

javascript - 数组排序不适用于 Android 手机,但适用于模拟器和 AIR

android - 如何在 Android 布局中自动执行 `layout_below` 顺序控件?

java - Android:从未使用过 IntelliJ IDEA 12.1 参数 View