简体   繁体   中英

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?

Maybe with:

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

instead of:

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

in your else condition.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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