2

I'm trying to add multiple layouts dynamically under each other. So I wrote the following code:

   for (int i = 1; i <= layoutCounter; i++) {
        View neu = inflater.inflate(R.layout.vote, parent, false);
        neu.setId(layoutID);

        if (layoutID == 1) {
            params = new RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.WRAP_CONTENT,
                    RelativeLayout.LayoutParams.WRAP_CONTENT);
            params.addRule(RelativeLayout.BELOW, R.id.txtMultiline);

        } else {

            params = new RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.WRAP_CONTENT,
                    RelativeLayout.LayoutParams.WRAP_CONTENT);
            params.addRule(RelativeLayout.BELOW, neu.getId());

        }
        neu.setLayoutParams(params);
        parent.addView(neu);

        layoutID++;
    }

txtMultiline is a fixed View defined in XML. LayoutID is an integer and starts with 1. The first layout is added correctly under the txtMultiline TextView. But all following layouts just get added on top of the parent layout (which is a RelativeLayout). Can't get the reason.. else-route is executed correctly. But the BELOW constant seems to have no effect when trying to apply it to my dynamically inflated layouts. What am I doing wrong?

Droidman
  • 11,485
  • 17
  • 93
  • 141

2 Answers2

5

Maybe with:

params.addRule(RelativeLayout.BELOW, layoutID-1);

instead of:

params.addRule(RelativeLayout.BELOW, neu.getId());

in your else condition.

SylvainL
  • 3,926
  • 3
  • 20
  • 24
  • thanks! Made an idiotic mistake. I used getId() before the ID actually got incremented >< Sure I should use your solution – Droidman Jan 03 '13 at 15:07
0

You can try like this

RelativeLayout.LayoutParams rl = new RelativeLayout.LayoutParams(...)


rl.addRule(RelativeLayout.BELOW, anotherview.getId())
rl.addRule(RelativeLayout.ALIGN_PARENT_LEFT)

parentLayout.addView(myView, rl)
Blackbelt
  • 156,034
  • 29
  • 297
  • 305
Janmejoy
  • 2,721
  • 1
  • 20
  • 38