Adding child views to Relative Layout

后端 未结 2 1756
野的像风
野的像风 2021-01-25 04:43

Though I have been through many questions regarding relative layout and adding child view programatically, I am unable to resolve this issue

for (int i=0; i

        
相关标签:
2条回答
  • 2021-01-25 04:55

    Create new instances of ImageView and TextView inside the loop

    for (int i = 0; i < views; i++) {
        LayoutParams img_params= new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        img_params.addRule(RelativeLayout.ALIGN_PARENT_LEFT|RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
        ImageView img = new ImageView(this);
        relativeLayout.addView(img, img_params);
    
        LayoutParams text_params= new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        text_params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT|RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
        TextView textview = new TextView(this);
        relativeLayout.addView(textview, text_params);
    }
    
    0 讨论(0)
  • 2021-01-25 04:57

    You're adding the same View objects in a loop over and over. The first time the loop runs the two Views are added and they now have a parent. They cant be added again.

    You'll need to instantiate new instances of those views in every iteration for this to work.

    0 讨论(0)
提交回复
热议问题