简体   繁体   English

将子视图添加到相对布局

[英]Adding child views to Relative Layout

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<views; i++) {

    ImageView img = new ImageView(this);
    LayoutParams img_params= new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    img_params.addRule(RelativeLayout.ALIGN_PARENT_LEFT|RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
    relativeLayout.addView(img, img_params);

    TextView textview = new TextView(this);
    LayoutParams text_params= new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    text_params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT|RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
    relativeLayout.addView(textview, text_params);
}

I have added log below: 我在下面添加了日志:

06-27 11:16:38.849: E/AndroidRuntime(20595): java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.

You're adding the same View objects in a loop over and over. 您要一遍又一遍地添加相同的View对象。 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. 您需要在每次迭代中实例化这些视图的新实例,以使其工作。

Create new instances of ImageView and TextView inside the loop 在循环内创建ImageViewTextView新实例

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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