Android 异常java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState

项目中发现重复跳转一个Fragment出现改异常

  Caused by: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
 at android.support.v4.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1489)
 at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1507)
 at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:634)
 at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:613)

这个问题是在使用FragmentTransaction的commit()时出现的异常。网上找了一下资料,顺便看了下源码。发现源码上已有解决方案

  /**
     * Schedules a commit of this transaction.  The commit does
     * not happen immediately; it will be scheduled as work on the main thread
     * to be done the next time that thread is ready.
     *
     * <p class="note">A transaction can only be committed with this method
     * prior to its containing activity saving its state.  If the commit is
     * attempted after that point, an exception will be thrown.  This is
     * because the state after the commit can be lost if the activity needs to
     * be restored from its state.  See {@link #commitAllowingStateLoss()} for
     * situations where it may be okay to lose the commit.</p>
     * 
     * @return Returns the identifier of this transaction's back stack entry,
     * if {@link #addToBackStack(String)} had been called.  Otherwise, returns
     * a negative number.
     */
    public abstract int commit();

    /**
     * Like {@link #commit} but allows the commit to be executed after an
     * activity's state is saved.  This is dangerous because the commit can
     * be lost if the activity needs to later be restored from its state, so
     * this should only be used for cases where it is okay for the UI state
     * to change unexpectedly on the user.
     */
    public abstract int commitAllowingStateLoss();

上面2个方法得大概意思是说我使用的 commit方法是在Activity的onSaveInstanceState()之后调用的,这样会出错,因为onSaveInstanceState方法是在该Activity即将被销毁前调用,来保存Activity数据的,如果在保存玩状态后再给它添加Fragment就会出错。if the activity needs to be restored from its state. See {@link #commitAllowingStateLoss()} 。so,把commit换成commitAllowingStateLoss()运行就解决了该bug,记录一下。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值