android dynamically add layouts under each other

谁说胖子不能爱 提交于 2019-12-19 04:15:18

问题


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?


回答1:


Maybe with:

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

instead of:

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

in your else condition.




回答2:


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)


来源:https://stackoverflow.com/questions/14139214/android-dynamically-add-layouts-under-each-other

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!