Fragment切换:java.lang.IllegalStateException: The specified child already has a parent. You must ca...

完整的异常信息

 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:5099)
        at android.view.ViewGroup.addView(ViewGroup.java:4930)
        at android.view.ViewGroup.addView(ViewGroup.java:4870)
        at android.view.ViewGroup.addView(ViewGroup.java:4843)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1434)
        at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1759)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1827)
        at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:797)
        at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2596)
        at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2383)
        at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2338)
        at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2245)
        at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:703)
        at android.os.Handler.handleCallback(Handler.java:891)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:207)
        at android.app.ActivityThread.main(ActivityThread.java:7470)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:958)

发生场景

  • 带有转场动画的fragment快速切换(包含回退)
    具体问题代码片段

fragment 容器

public class ContainerActivity extends BaseActivity {
    private FrameLayout mContainer;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sample_activity_container);
        mContainer = findViewById(R.id.fl_container);
    }


    /**
     * The specified child already has a parent. You must call removeView() on the child's parent first.
     * 发生场景: 需要持有几个fragment,来回快速切换(包含回退),并且有有转场动画的场景下,就会出现此问题
     */
    private Fragment fragment00, fragment01, fragment02;

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    private void openTestFragment(boolean isNeedAnimation, int type) {
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction ft = manager.beginTransaction();
        //设置替换和退栈的动画
        if (isNeedAnimation) {
            ft.setCustomAnimations(R.anim.sample_anim_right_in, R.anim.sample_anim_right_out, R.anim.sample_anim_left_in, R.anim.sample_anim_left_out);
        }
        Fragment tempFragment = null;
        switch (type) {
            case 0:
                fragment00 = manager.findFragmentByTag("" + type);
                if (fragment00 == null) {
                    fragment00 = TestFragment.newInstance(type);
                } else {
                    Log.d("Test", "fragment00 不为空");
                }
                tempFragment = fragment00;
                break;
            case 1:
                fragment01 = manager.findFragmentByTag("" + type);
                if (fragment01 == null) {
                    fragment01 = TestFragment.newInstance(type);
                } else {
                    Log.d("Test", "fragment01 不为空");
                }
                tempFragment = fragment01;
                break;
            case 2:
                fragment02 = manager.findFragmentByTag("" + type);
                if (fragment02 == null) {
                    fragment02 = TestFragment.newInstance(type);
                } else {
                    Log.d("Test", "fragment02 不为空");
                }
                tempFragment = fragment02;
                break;
            default:
                Log.d("Test", "异常");
                tempFragment = TestFragment.newInstance(type);
                break;
        }


        ft.replace(R.id.fl_container, tempFragment, "" + type);
        if (isNeedAnimation) {
            ft.addToBackStack(null);
        }
        if (isDestroyed() || isFinishing()) {
            return;
        }
        ft.commitAllowingStateLoss();
    }

    public int i = 0;

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    public void switchFragment(View view) {
        openTestFragment(true, i % 3);
        i++;
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (i > 0)
            i--;
    }

fragment

public class TestFragment extends BaseFragment {

    private static final String TYPE_KEY = "type_key";
    private View mVRoot;
    private int mType;

    public static TestFragment newInstance( int type) {
        TestFragment fragment = new TestFragment();
        Bundle info = new Bundle();
        info.putInt(TYPE_KEY, type);
        fragment.setArguments(info);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle arguments = getArguments();
        if (arguments != null) {
            mType = arguments.getInt(TYPE_KEY);
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        if (mVRoot == null) {
            log("mVRoot 为空");
            mVRoot = inflater.inflate(R.layout.sample_fragment_test, container, false);
            initView(mVRoot);
        } else {
            ViewGroup parentView = (ViewGroup) mVRoot.getParent();
            if (parentView != null) {
                //The specified child already has a parent. You must call removeView() on the child's parent first.
                parentView.removeView(mVRoot);//这样操作,有动画且动画尚未结束的场景下是remove不掉的,就会产生上面的崩溃信息

            }
        }
        initData();
        return mVRoot;
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    private void initData() {

    }

    private void initView(View view) {
        TextView textView = view.findViewById(R.id.tv_test);
        textView.setText("当前位置" + mType);
    }

  
}

发生原因

  • 快速切换转场动画尚未结束,removeView无效,造成同一个view尚未被移除出上一个parent,就被添加到下一个parent,从而引发此异常现象。

removeView 源码分析

  • step1
    @Override
    public void removeView(View view) {
        if (removeViewInternal(view)) {
            requestLayout();
            invalidate(true);
        }
    }
  • step2
 private void removeViewInternal(int index, View view) {
        if (mTransition != null) {
            mTransition.removeChild(this, view);
        }

      ····略

        if (view.getAnimation() != null ||
                (mTransitioningViews != null && mTransitioningViews.contains(view))) {
            addDisappearingView(view);
        } else if (view.mAttachInfo != null) {
           view.dispatchDetachedFromWindow();
        }

     ····略
    }

可以看出如果有动画是走了addDisappearingView(view)

  • step3
    /**
     * Add a view which is removed from mChildren but still needs animation
     *
     * @param v View to add
     */
    private void addDisappearingView(View v) {
        ArrayList<View> disappearingChildren = mDisappearingChildren;

        if (disappearingChildren == null) {
            disappearingChildren = mDisappearingChildren = new ArrayList<View>();
        }

        disappearingChildren.add(v);
    }

就是添加到了一个集合里面,然后看看用这个集合都做了什么。

  • step 4
 @Override
    protected void dispatchDraw(Canvas canvas) {
        ····略

        // Draw any disappearing views that have animations
        if (mDisappearingChildren != null) {
            final ArrayList<View> disappearingChildren = mDisappearingChildren;
            final int disappearingCount = disappearingChildren.size() - 1;
            // Go backwards -- we may delete as animations finish
            for (int i = disappearingCount; i >= 0; i--) {
                final View child = disappearingChildren.get(i);
                more |= drawChild(canvas, child, drawingTime);
            }
        }
        ····略
    }

可以看出这些view 还是被画出来了,并没有被实际移除

  • step 5
    public void endViewTransition(View view) {
        if (mTransitioningViews != null) {
            mTransitioningViews.remove(view);
            final ArrayList<View> disappearingChildren = mDisappearingChildren;
            if (disappearingChildren != null && disappearingChildren.contains(view)) {
                disappearingChildren.remove(view);
                if (mVisibilityChangingChildren != null &&
                        mVisibilityChangingChildren.contains(view)) {
                    mVisibilityChangingChildren.remove(view);
                } else {
                    if (view.mAttachInfo != null) {
                        view.dispatchDetachedFromWindow();
                    }
                    if (view.mParent != null) {
                        view.mParent = null;
                    }
                }
                invalidate();
            }
        }
    }
    private LayoutTransition.TransitionListener mLayoutTransitionListener =
            new LayoutTransition.TransitionListener() {
        @Override
        public void startTransition(LayoutTransition transition, ViewGroup container,
                View view, int transitionType) {
            // We only care about disappearing items, since we need special logic to keep
            // those items visible after they've been 'removed'
            if (transitionType == LayoutTransition.DISAPPEARING) {
                startViewTransition(view);
            }
        }

        @Override
        public void endTransition(LayoutTransition transition, ViewGroup container,
                View view, int transitionType) {
            if (mLayoutCalledWhileSuppressed && !transition.isChangingLayout()) {
                requestLayout();
                mLayoutCalledWhileSuppressed = false;
            }
            if (transitionType == LayoutTransition.DISAPPEARING && mTransitioningViews != null) {
                endViewTransition(view);
            }
        }
    };

动画结束的时候才是真正的被移除
最后也可以追溯下fragment添加动画,最终是调用的


    public void startViewTransition(View view) {
        if (view.mParent == this) {
            if (mTransitioningViews == null) {
                mTransitioningViews = new ArrayList<View>();
            }
            mTransitioningViews.add(view);
        }
    }

处理方案1:

在fragment 复写此方法,添加如下逻辑,亲测有效(未看源码)

    @Override
    public void onDestroyView() {
        super.onDestroyView();

        if(mVRoot!=null){
            ViewGroup parentView = (ViewGroup) mVRoot.getParent();
            if (parentView != null) {
                parentView.removeView(mVRoot);
                log("onDestroyView  mVRoot  parentView 不为空,onDestroyView里面  走了移除逻辑");
            } else {
                log("onDestroyView  mVRoot  parentView 为空");
            }
        }

    }

处理方案2:

经过上面的源码分析很显然了,主动调用下清除转场动画的view就行了endViewTransition

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        if (mVRoot == null) {
            log("mVRoot 为空");
            mVRoot = inflater.inflate(R.layout.sample_fragment_test, container, false);
            initView(mVRoot);
        } else {
            ViewGroup parentView = (ViewGroup) mVRoot.getParent();
            if (parentView != null) {
                //The specified child already has a parent. You must call removeView() on the child's parent first.
                parentView.endViewTransition(mVRoot);//主动调用清除动画
                parentView.removeView(mVRoot);

            }
        }
        initData();
        return mVRoot;
    }
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,242评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,769评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,484评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,133评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,007评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,080评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,496评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,190评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,464评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,549评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,330评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,205评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,567评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,889评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,160评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,475评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,650评论 2 335

推荐阅读更多精彩内容