方向改变崩溃后更换碎片

时间:2018-10-16 12:35:29

标签: java android kotlin

当用户更改屏幕方向并执行“ goToDetails”时,FragmentManager会抛出

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

类代码:

@ActivityScope
class NavigatorImpl @Inject constructor(): ActivityLifecycleTask(), Navigator {

private lateinit var fragmentManager: FragmentManager

@IdRes
private var fragmentContainerRes: Int = 0

override fun onCreate(activity: BaseActivity) {
    fragmentManager = activity.supportFragmentManager
    fragmentContainerRes = activity.fragmentContainerRes()
}

override fun init(fragment: BaseFragment) {
    goToFragment(fragment, TAG_INIT_FRAGMENT)
}

override fun goToDetails(id: Long) {
    goToFragment(DetailsFragment.create(id))
}

private fun goToFragment(fragment: Fragment, tag: String? = null) {
    Log.d(javaClass.simpleName, "goToFragment")
    fragmentManager.beginTransaction()
            .add(fragmentContainerRes, fragment, tag)
            .addToBackStack(null)
            .commit()
}

companion object {
    private const val TAG_INIT_FRAGMENT = "TAG_INIT_FRAGMENT"
}
}

commitAllowingInstanceStateLoss()不起作用。 onCreate(activity)在活动onCreate回调中执行。然后在savedInstanceState == null期间,执行NavigatorImpl中的init()

1 个答案:

答案 0 :(得分:2)

旋转屏幕时,将执行“活动”的onCreate,但不会执行savedInstanceState。如果您不检查它是否虚假,您仍将尝试进行新的事务以启动您的主动性。因此,您应该在初始化片段之前检查是否null

savedInstanceState == null