Dynamically add layouts (Relative Layouts) beneath

2019-08-15 11:16发布

问题:

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++;
    }

}