Search code examples
androidandroid-relativelayoutlayout-inflater

android dynamically add layouts under each other


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?


Solution

  • Maybe with:

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

    instead of:

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

    in your else condition.