以编程方式设置 GridLayout 子项的 rowSpan 或 colSpan? [英] Set rowSpan or colSpan of a child of a GridLayout programmatically?

查看:31
本文介绍了以编程方式设置 GridLayout 子项的 rowSpan 或 colSpan?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a GridLayout with 5 columns and 3 rows. Now I can insert arbitrary child views, which is great. Even better is, that I can assign columnSpan=2 to some item in order to span it to 2 columns (the same with rowSpan).

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

The problem now is, that I cannot assign rowSpan or columnSpan programmatically (i.e. at runtime). Some search suggested something like this:

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

但是我不太明白spec的参数是什么意思(开始和大小).在这一点上,文档也很差.

But I don't quite understand what the parameters of spec mean (start and size). The documentation is also quite poor at this point.

非常感谢任何帮助!

推荐答案

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

OK, I spent some hours figuring out what's going on here. Well, I didn't find any working way to set columnSpan or rowSpan at runtime.

但我找到了一个有效的解决方案(至少对我来说):

But I found a solution that works (at least for me):

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() 将视图添加到根元素(即父元素).

Hint: It's very important, that you set the width and height attribute, before inflate() adds the view to the root element (i.e. the parent element).

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

I hope, someone can use this ;-)

这篇关于以编程方式设置 GridLayout 子项的 rowSpan 或 colSpan?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆