Dynamically add layouts (Relative Layouts) beneath each other in Android

北战南征 提交于 2019-12-24 18:09:06

问题


I am trying to create a method where each time I click a button, I want the screen to display a Relative Layout box below one that is currently there or create one at the top if there isn't one there and I want it to keep creating them below from each button click. Currently using this method, nothing happens when the button is clicked.

Here is the code that I have so far and can someone please help me see what I am doing wrong and what I can do to fix this issue:

public void createNewLayout(){

    int currentId = 10;

    for(int i = 1; i <= numberOfLayouts; i++){
        newLayoutContainer = new RelativeLayout(this);
        newLayoutContainer.setId(currentId);

        if(currentId == 10){
            newLayoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, dpContainerHeight);
            newLayoutParams.addRule(RelativeLayout.ALIGN_LEFT, containerLayout2.getId());
            newLayoutParams.addRule(RelativeLayout.ALIGN_RIGHT, containerLayout2.getId());
            newLayoutParams.addRule(RelativeLayout.BELOW, containerLayout2.getId());
            newLayoutParams.setMargins(0, 0, 0, dpMargin);
            newLayoutContainer.setBackgroundResource(R.color.display_panels);
        }

        else{
            newLayoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, dpContainerHeight);
            newLayoutParams.addRule(RelativeLayout.ALIGN_LEFT, newLayoutContainer.getId());
            newLayoutParams.addRule(RelativeLayout.ALIGN_RIGHT, newLayoutContainer.getId());
            newLayoutParams.addRule(RelativeLayout.BELOW, currentId-1);
            newLayoutParams.setMargins(0, 0, 0, dpMargin);
            newLayoutContainer.setBackgroundResource(R.color.display_panels);
        }

        newLayoutContainer.setLayoutParams(newLayoutParams);
        layout.addView(newLayoutContainer);

        currentId++;
    }

}

来源:https://stackoverflow.com/questions/17548208/dynamically-add-layouts-relative-layouts-beneath-each-other-in-android

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