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)

發(fā)生場(chǎng)景

  • 帶有轉(zhuǎn)場(chǎng)動(dòng)畫(huà)的fragment快速切換(包含回退)
    具體問(wèn)題代碼片段

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.
     * 發(fā)生場(chǎng)景: 需要持有幾個(gè)fragment,來(lái)回快速切換(包含回退),并且有有轉(zhuǎn)場(chǎng)動(dòng)畫(huà)的場(chǎng)景下,就會(huì)出現(xiàn)此問(wèn)題
     */
    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();
        //設(shè)置替換和退棧的動(dòng)畫(huà)
        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);//這樣操作,有動(dòng)畫(huà)且動(dòng)畫(huà)尚未結(jié)束的場(chǎng)景下是remove不掉的,就會(huì)產(chǎn)生上面的崩潰信息

            }
        }
        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("當(dāng)前位置" + mType);
    }

  
}

發(fā)生原因

  • 快速切換轉(zhuǎn)場(chǎng)動(dòng)畫(huà)尚未結(jié)束,removeView無(wú)效,造成同一個(gè)view尚未被移除出上一個(gè)parent,就被添加到下一個(gè)parent,從而引發(fā)此異常現(xiàn)象。

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();
        }

     ····略
    }

可以看出如果有動(dòng)畫(huà)是走了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);
    }

就是添加到了一個(gè)集合里面,然后看看用這個(gè)集合都做了什么。

  • 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 還是被畫(huà)出來(lái)了,并沒(méi)有被實(shí)際移除

  • 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);
            }
        }
    };

動(dòng)畫(huà)結(jié)束的時(shí)候才是真正的被移除
最后也可以追溯下fragment添加動(dòng)畫(huà),最終是調(diào)用的


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

處理方案1:

在fragment 復(fù)寫(xiě)此方法,添加如下邏輯,親測(cè)有效(未看源碼)

    @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:

經(jīng)過(guò)上面的源碼分析很顯然了,主動(dòng)調(diào)用下清除轉(zhuǎn)場(chǎng)動(dòng)畫(huà)的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);//主動(dòng)調(diào)用清除動(dòng)畫(huà)
                parentView.removeView(mVRoot);

            }
        }
        initData();
        return mVRoot;
    }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容