Android Fragment所遇问题(1)

使用:

		 //获取Fragment管理器
        val mFragmentManager = supportFragmentManager
        //开启事务
        val mTransaction = mFragmentManager.beginTransaction()
    	.....
		 mTransaction.commitAllowingStateLoss()

为什么不使用commit而是用commitAllowingStateLoss()

FragmentTransaction.java

    public abstract int commitAllowingStateLoss();

实现类:BackStackRecord.java

 @Override
    public int commitAllowingStateLoss() {
        return commitInternal(true);
    }
 int commitInternal(boolean allowStateLoss) {
        if (mCommitted) throw new IllegalStateException("commit already called");
        if (FragmentManagerImpl.DEBUG) {
            Log.v(TAG, "Commit: " + this);
            LogWriter logw = new LogWriter(TAG);
            PrintWriter pw = new PrintWriter(logw);
            dump("  ", pw);
            pw.close();
        }
        mCommitted = true;
        if (mAddToBackStack) {
            mIndex = mManager.allocBackStackIndex(this);
        } else {
            mIndex = -1;
        }
        mManager.enqueueAction(this, allowStateLoss);
        return mIndex;
    }

FragmentManagerImpl.java

 public void enqueueAction(OpGenerator action, boolean allowStateLoss) {
        if (!allowStateLoss) {
        	//关键不同在于该方法
            checkStateLoss();
        }
        synchronized (this) {
            if (mDestroyed || mHost == null) {
                if (allowStateLoss) {
                    // This FragmentManager isn't attached, so drop the entire transaction.
                    return;
                }
                throw new IllegalStateException("Activity has been destroyed");
            }
            if (mPendingActions == null) {
                mPendingActions = new ArrayList<>();
            }
            mPendingActions.add(action);
            scheduleCommit();
        }
    }

  private void checkStateLoss() {
        if (isStateSaved()) {
            throw new IllegalStateException(
                    "Can not perform this action after onSaveInstanceState");
        }
    }
  @Override
    public boolean isStateSaved() {
        // See saveAllState() for the explanation of this.  We do this for
        // all platform versions, to keep our behavior more consistent between
        // them.
        return mStateSaved || mStopped;
    }
 Parcelable saveAllState() {
    ......

        mStateSaved = true;

mStateSaved 是又saveAllState()决定的,其他状态都是false。而 saveAllState()发生在所依托的Activity调用onSaveInstanceState()。 所以commit()和commitAllowingStateLoss()的差别是是否允许Fragment是被丢失过的。

问题2:Frgament的重叠
参考链接
Fragment的Hidden默认是false,而且FragmentState没有这个词条,导致了hide的Fragement在onSaveInstanceState()后出现Fragment重叠现象。

在这里插入图片描述
下面这个音乐播放进度控制是不应该出现在这里。发生了Fragment重叠。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值