以编程方式设置 GridLayout 子项的 rowSpan 或 colSpan?

新手上路,请多包涵

我有一个 GridLayout 有 5 列和 3 行。现在我可以插入任意子视图,这很棒。更好的是,我可以将 columnSpan=2 分配给某个项目,以便将其跨越到 2 列(与 rowSpan 相同)。

现在的问题是,我无法以编程方式(即在运行时)分配 rowSpan 或 columnSpan。一些搜索建议是这样的:

 layoutParams.columnSpec = GridLayout.spec(0, columnSpan);

但是不太明白spec的参数是什么意思(start和size)。在这一点上,文档也很差。

非常感谢任何帮助!

原文由 The_Unknown 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1k
2 个回答

好的,我花了几个小时弄清楚这里发生了什么。好吧,我没有找到任何在运行时设置 columnSpan 或 rowSpan 的有效方法。

但我找到了一个可行的解决方案(至少对我而言):

Java代码

private LinearLayout addNewSpannedView(Integer resourceId, ViewGroup rootElement) {
    return (LinearLayout) ((ViewGroup) getLayoutInflater().inflate(resourceId, rootElement, true)).getChildAt(rootElement.getChildCount() - 1);
}
// set columnSpan depending on some logic (gridLayout is the layout to add the view's to -> in my case these are LinearLayouts)
shape = addNewSpannedView(columnSpan == 1 ? R.layout.grid_ll_col_span_1 : R.layout.grid_ll_col_span_2, gridLayout);

grid_ll_col_span_2.xml

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="@dimen/shapeWidth"
    android:layout_height="wrap_content"
    android:layout_columnSpan="2"/>

提示:在 inflate() 将视图添加到根元素(即父元素) 之前,设置宽度和高度属性非常重要。

我希望有人可以使用它 ;-)

原文由 The_Unknown 发布,翻译遵循 CC BY-SA 3.0 许可协议

    GridLayout gridLayout = (GridLayout)findViewById(R.id.tableGrid);

    gridLayout.removeAllViews();

    int total = 12;
    int column = 5;
    int row = total / column;
    gridLayout.setColumnCount(column);
    gridLayout.setRowCount(row + 1);
    for(int i =0, c = 0, r = 0; i < total; i++, c++)
    {
        if(c == column)
        {
            c = 0;
            r++;
        }
        ImageView oImageView = new ImageView(this);
        oImageView.setImageResource(R.drawable.ic_launcher);
        GridLayout.LayoutParams param =new GridLayout.LayoutParams();
        param.height = LayoutParams.WRAP_CONTENT;
        param.width = LayoutParams.WRAP_CONTENT;
        param.rightMargin = 5;
        param.topMargin = 5;
        param.setGravity(Gravity.CENTER);
        param.columnSpec = GridLayout.spec(c);
        param.rowSpec = GridLayout.spec(r);
        oImageView.setLayoutParams (param);
        gridLayout.addView(oImageView);
    }

查看此图像 - 您可以根据需要更改行数和列数

原文由 Nikhil Pingle 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题