Ben Ezard Ben Ezard - 1 year ago 94
Android Question

Reparenting a View in Android not working

So I have code like such:

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

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

However, the following
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 Source


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() {
}, 350);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download