FragmentManager已经在commitAllowingStateLoss()上执行事务

时间:2018-03-28 08:24:57

标签: android android-fragments fragmentmanager

java.lang.IllegalStateException: FragmentManager is already executing transactions

我已经阅读了有关该问题的所有StackOverflow问题,但没有任何帮助。 只是想分享我的经验

public void onResume() {
    super.onResume()

    if(condition) replaceFragment()
}

public void replaceFragment() {
    if (fragmentName != null && !this.isDestroyed()) {
        final FragmentTransaction ft = getSupportFragmentManager().beginTransaction();

        ft.replace(container_id, FragmentInstantiate());
        ft.commitAllowingStateLoss();
    }
}

是commit()/ commitAllowingStateLoss()导致IllegalStateException:FragmentManager已经在执行事务。不是commitNow()或executePendingTransactions()

1 个答案:

答案 0 :(得分:6)

<强>问题: 问题是在Fragment.onResume()方法中执行replaceFragment()的同步

override fun onResume() {
    super.onResume()

    if(condition) replaceFragment()
}

<强>解

override fun onResume() {
    super.onResume()

    if(condition) {
        Observable.fromCallable{}
                  .observeOn(AndroidSchedulers.mainThread())
                  .subscribe { replaceFragment() }
}

或使用Handler推迟执行replaceFragment()

 new Handler().post { replaceFragment() };