dcanh121
dcanh121

Reputation: 4695

Add child view to two layouts (multiple parents)

I want to add the same view to a new RelativeLayout which is added earlier to another.

 RelativeLayout1
   -- View1
   -- ScrollView
      -- Linear Layout2

I have a view added to linear layout2 which is added to the scrollview. I want to add the same child view to the RelativeLayout1 in the place of View1.

I add the views this way,

MyCustomScrollView scrollView = new MyCustomScrollView(context);
  layout2 = new LinearLayout(context);

  for(int i=0;i<10;i++)
     layout2.addView(list.get(i));

  scrollView,add(layout2);
  relativeLayout1.addView(scrollView);

Now I want to add the same view from list to RelativeLayout1 in the place of View1

 RelativeLayout1.remove(view1);
 RelativeLayout1.addView(list.get(0),0);



Causes 

java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
    at android.view.ViewGroup.addViewInner(ViewGroup.java:2062)
    at android.view.ViewGroup.addView(ViewGroup.java:1957)
    at android.view.ViewGroup.addView(ViewGroup.java:1914)

Upvotes: 1

Views: 2493

Answers (1)

CommonsWare
CommonsWare

Reputation: 1007379

A View cannot be a child of two ViewGroup parents.

Feel free to clone the View and add the clone to the second parent.

Upvotes: 7

Related Questions