简体   繁体   English

以编程方式在RelativeLayout中添加子视图

[英]Add child views in RelativeLayout programmatically

I have a function that loops over a list and returns the row elements. 我有一个循环遍历列表并返回行元素的函数。

I want to add these rows to an empty RelativeLayout one by one, so that all the rows are displayed sequentially vertically. 我想将这些行一个接一个地添加到一个空的RelativeLayout ,以便所有行都按顺序垂直显示。

But the code below is not working. 但是下面的代码不起作用。

void setRows(RelativeLayout rowContainer, ViewHolder viewHolder, 
    List<RowCollection> rowCollection) {

    for (int i = 0; i < rowCollection.size(); i++) {
        MyRow row = new MyRow(rowCollection.get(i));
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, row.getId());
        rowContainer.addView(row, params);
    }
}

Only the last row element is displayed. 仅显示最后一行元素。

I guess but am not sure, that the rows are overlapping each other. 我猜但不确定行是否相互重叠。

You are placing all your Views to the Bottom of the RelativeLayout, so they are always on top of the other. 您将所有视图放置在RelativeLayout的底部,因此它们始终位于另一个视图的顶部。 So there is always only the last one visible because the other ones are blow it. 所以总是只有最后一个可见,因为其他的都把它吹了。 Change your Code to this: 将您的代码更改为此:

 params.addRule(RelativeLayout.BELOW, iDFromPreviousView);

change to: 改成:

void setRows(RelativeLayout rowContainer, ViewHolder viewHolder,
        List<RowCollection> rowCollection) {
            MyRow lat_row=null;
    for (int i = 0; i < rowCollection.size(); i++) {
        MyRow row = new MyRow(rowCollection.get(i));
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        if (i == 0) {
            params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        }else{

            //<---get the id of previous row not sure what RowCollection contains 
            params.addRule(RelativeLayout.ABOVE,lat_row.getId());
        }
                    lat_row=row;
        rowContainer.addView(row, params);
    }
}

this will stack all the view from bottom to top. 这将从底部到顶部堆叠所有视图。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM