我有一个GridLayout
有5列3行。 现在我可以插入任意子视图,这是伟大的。 更妙的是,我可以分配columnSpan=2
,以它跨越到2列(与行跨度相同的)一些项目。
现在的问题是,我不能指定ROWSPAN或columnSpan编程方式(即在运行时)。 一些搜索建议是这样的:
layoutParams.columnSpec = GridLayout.spec(0, columnSpan);
但我不太明白什么规格平均值的参数(启动和大小)。 该文件还在这一点上相当差。
任何帮助,不胜感激!
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);
}
这个怎么样?
GridLayout.LayoutParams layoutParams = new GridLayout.LayoutParams();
layoutParams.rowSpec = GridLayout.spec(GridLayout.UNDEFINED, item.getRowSpan());
layoutParams.columnSpec = GridLayout.spec(GridLayout.UNDEFINED, item.getColumnSpan());
根据文件,你也应该呼吁网格布局setLayoutParams如果更改列或行范围后面的子视图插入到网格布局。 如果您添加它们,同时设置跨度你不需要这个
您可以修改网格布局layout_rowSpan属性是这样的:
// View allocated in first row and first column
View child = findViewById(R.id.row0column0);
GridLayout.LayoutParams params =
new GridLayout.LayoutParams(child.getLayoutParams());
params.rowSpec = GridLayout.spec(0, 2); // First cell in first row use rowSpan 2.
params.columnSpec = GridLayout.spec(0, 2); // First cell in first column use columnSpan 2.
child.setLayoutParams(params);
我同意文档需要在这方面有点改进。
我在编程和充气后更改列跨度约2格这段代码:
GridLayout.LayoutParams itemLP = (GridLayout.LayoutParams)gridItemV.getLayoutParams();
itemLP.columnSpec = GridLayout.spec(0, 2);
gridItemV.setLayoutParams(itemLP);
重要的是呼叫setLayoutParams
变更后columnSpec
我希望它也有助于你
OK,我花了一些时间搞清楚什么是怎么回事。 好吧,我没有找到任何工作方式设置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"/>
提示:这是非常重要的,你设置的宽度和高度属性, 之前膨胀()将着眼于根元素(即父元素)。
我希望有人可以使用此;-)