Ben Ezard Ben Ezard - 5 months ago 23
Android Question

Reparenting a View in Android not working

So I have code like such:

((LinearLayout) view.getParent()).removeView(view);
container.addView(view);


Now, correct me if I'm wrong, but that code should remove the view from its current
ViewGroup
, then add it to a new
ViewGroup


However, the following
exception
is raised:

E/AndroidRuntime(31220): java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.


Any ideas on why this could be happening please?

EDIT: This only happens when android:animateLayoutChanges is set to true in the parent's XML tag

Answer

Solved:

Due to the animation, the View isn't actually removed until the animation finishes, which takes about 300ms

So something like this should work fine (350ms timer just to make sure the animation has finished):

((ViewGroup) view.getParent()).removeView(view);
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
    public void run() {
        container.addView(view);
    }
}, 350);