-3

I am creating view via XML.

But after adding view it is throwing error -

The specified child already has a parent. You must call removeView() on the child's parent first.

I am using below code -

LinearLayout main = new LinearLayout(mContext);
main.setId(R.id.main);
main.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
main.setLayoutParams(layoutParams);

LinearLayout sub1 = new LinearLayout(mContext);
sub1.setId(R.id.sub1);
sub1.setOrientation(LinearLayout.HORIZONTAL);
LinearLayout.LayoutParams layout_662 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
sub1.setLayoutParams(layout_662);


LinearLayout sub2 = new LinearLayout(mContext);
sub2.setId(R.id.sub2);
sub2.setOrientation(LinearLayout.HORIZONTAL);
LinearLayout.LayoutParams layout_943 = new  LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
sub2.setLayoutParams(layout_943);

for(int i=0;i<=4);i++) {

    sub1.addView(imageView[i]);
    main.addView(sub1);

    sub2.addView(imageView1[i]);
    main.addView(sub2);
}

Any kind of help will be appreciated.

Denysole
  • 3,903
  • 1
  • 20
  • 28
Chandan Wadhwa
  • 196
  • 2
  • 13

3 Answers3

1

Change your for statement this way:

    main.addView(sub1);
    main.addView(sub2);

    for(int i=0;i<=4);i++) {

        sub1.addView(imageView[i]);

        sub2.addView(imageView1[i]);
    }

You have to add sub1 and sub2 only once.

Roberto Martucci
  • 1,237
  • 1
  • 13
  • 21
  • You're right, but if you look better at the code, they are two different arrays of images. So every image belongs to one only parent. imageview[] and imageview1(ONE)[] – Roberto Martucci Dec 05 '17 at 11:47
  • Well, probably it depends on your ImageViews' layout params...maybe you should check them. You could show the code where you create them – Roberto Martucci Dec 05 '17 at 11:57
  • By the way, from your code it seems that main view is not attached to any view...why don't you build your layout via xml? – Roberto Martucci Dec 05 '17 at 12:07
0

You've got

main.addView(sub1);

inside a for-loop. So on the second loop, it's already added to the parent view.

MSpeed
  • 8,153
  • 7
  • 49
  • 61
0

Use it like below.

 for(int i=0;i<=4);i++) {
        sub1.addView(imageView[i]);
        sub2.addView(imageView1[i]);
    }
    main.addView(sub1);
    main.addView(sub2);
ADM
  • 20,406
  • 11
  • 52
  • 83