reiley
reiley

Reputation: 3761

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.

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.

Upvotes: 1

Views: 1179

Answers (2)

Thommy
Thommy

Reputation: 5417

You are placing all your Views to the Bottom of the RelativeLayout, so they are always on top of the other. 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);

Upvotes: 3

vipul mittal
vipul mittal

Reputation: 17401

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.

Upvotes: 2

Related Questions