源码角度解释fragment的坑(二)

本文探讨了Fragment在使用中遇到的问题,包括按返回键时Fragment的处理方式及其生命周期变化。通过分析源码,揭示了Fragment是否加入回退栈如何影响其onDestroyView和onDestroy的调用。当Fragment被移除时,加入栈的只执行onDestroyView,而不加入的则执行onDestroy。源码中的switch case结构巧妙地处理了这些状态变化。
摘要由CSDN通过智能技术生成

如果你已经使用过fragment,我先提出几个问题。

1、按返回键的时候,如果当前的fragment是加入到栈的(其实这个说法不是很准确,因为真正加入栈的是操作fragment的事务),那么这个fragment会被remove掉,而如果没有加入栈,那么回退按键对这个fragment一点反应也没有?

2、加入到栈的fragment在被remove的时候,其生命周期走到onDestroyView而没有走到onDestroy,而没有加入栈的话,会走到onDestroy?

你可以先代码验证如上问题,然后自己寻找答案

下面是我读源码时候的理解;

1、按返回键,本质上是调用popBackStack(….)方法,最终会从事务栈中取出最近的一个事务,然后执行操作,如果当初add这个fragment的时候没有加入栈,当然从中找不到事务,也不会对当前fragment有影响。

部分代码如下:

boolean popBackStackState(Handler handler, String name, int id, int flags) {
        if (mBackStack == null) {
            return false;
        }
        if (name == null && id < 0 && (flags&POP_BACK_STACK_INCLUSIVE) == 0) {
            int last = mBackStack.size()-1;
            if (last < 0) {
                return false;
            }
            //取出最近的事务,BackStackRecord 其实对应的就是 FragmentTransaction
            final BackStackRecord bss = mBackStack.remove(last);
            SparseArray<Fragment> firstOutFragments = new SparseArray<Fragment>();
            SparseArray<Fragment> lastInFragments = new SparseArray<Fragment>();
            if (mCurState >= Fragment.CREATED) {
                bss.calculateBackFragments(firstOutFragments, lastInFragments);
            }
            bss.popFromBackStack(true, null, firstOutFragments, lastInFragments);
            reportBackStackChanged();
        }

2、加不加入到栈,会什么在remove操作时候,会影响到onDestroy生命周期,这个我们从源码看下,

2.1 先看removeFragment,看我的注释
 public void removeFragment(Fragment fragment, int transition, int transitionStyle) {
        if (DEBUG) Log.v(TAG, "remove: " + fragment + " nesting=" + fragment.mBackStackNesting);
        //此处关键,如果加入栈,inactive 为false,否则为true
        final boolean inactive = !fragment.isInBackStack();
        if (!fragment.mDetached || inactive) {
            if (mAdded != null) {
                mAdded.remove(fragment);
            }
            if (fragment.mHasMenu && fragment.mMenuVisible) {
                mNeedMenuInvalidate = true;
            }
            fragment.mAdded = false;
            fragment.mRemoving = true;
            //走到这个方法
            moveToState(fragment, inactive ? Fragment.INITIALIZING : Fragment.CREATED,
                    transition, transitionStyle, false);
        }
    }
  moveToState 方法,从上面传进来的newState,如果加入栈,其值为Fragment.CREATED,否则为Fragment.INITIALIZING

                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值