设备旋转时导航组件崩溃
2019-04-15 11:50:08.589 21493-21493/me.rankov.kaboom E/AndroidRuntime: FATAL EXCEPTION: main
Process: me.rankov.kaboom, PID: 21493
java.lang.IllegalArgumentException: navigation destination me.rankov.kaboom:id/actionHomeToCountry is unknown to this NavController
at androidx.navigation.NavController.navigate(NavController.java:803)
at androidx.navigation.NavController.navigate(NavController.java:744)
at androidx.navigation.NavController.navigate(NavController.java:730)
at androidx.navigation.NavController.navigate(NavController.java:718)
at me.rankov.kaboom.login.LoginActivity.navigateToRegister(LoginActivity.kt:22)
at me.rankov.kaboom.login.LoginPresenterImpl.checkRegistration(LoginPresenterImpl.kt:49)
at me.rankov.kaboom.login.LoginPresenterImpl.onStart(LoginPresenterImpl.kt:37)
at me.rankov.kaboom.login.LoginActivity.onStart(LoginActivity.kt:45)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1392)
at android.app.Activity.performStart(Activity.java:7231)
它在这里崩溃
override fun navigateToRegister(fragmentId: Int, bundle: Bundle) {
findNavController(R.id.login_host_fragment).navigate(fragmentId, bundle)
}
我通过主持人onStart事件调用它
val nickname = loginInteractor.getNickname()
val country = loginInteractor.getCountry()
when {
nickname.isEmpty() -> {
val bundle = bundleOf("user" to user)
loginView?.navigateToRegister(R.id.actionHomeToName, bundle)
}
country < 0 -> loginView?.navigateToRegister(R.id.actionHomeToCountry)
else -> loginView?.navigateToMain()
}
完整代码在这里:login activity和presenter
这是我的主机片段:
<fragment
android:id="@+id/login_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="395dp"
android:layout_height="322dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
app:defaultNavHost="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:navGraph="@navigation/login" />
这里是navigation graph。
无需更改方向即可按预期工作。
答案 0 :(得分:3)
更改配置后,导航控制器后堆栈有问题
在带有片段的活动中:尝试在更改配置之前保存导航控制器状态。更改配置后,再次将其添加回导航控制器。喜欢:
override fun onSaveInstanceState(savedInstanceState: Bundle) {
super.onSaveInstanceState(savedInstanceState)
savedInstanceState.putBundle("nav_state", fragment.findNavController().saveState())
}
override fun onRestoreInstanceState(savedInstanceState: Bundle) {
super.onRestoreInstanceState(savedInstanceState)
fragment.findNavController().restoreState(savedInstanceState.getBundle("nav_state"))
}
那是我的情况
答案 1 :(得分:1)
这是因为您没有在<activity
android:name=".StreamActivity"
...
android:configChanges="keyboardHidden|orientation|screenSize" />
上指定操作。
LoginNameFragment
答案 2 :(得分:0)
使用这些依赖版本
implementation "androidx.navigation:navigation-fragment-ktx:2.3.0-alpha04"
implementation "androidx.navigation:navigation-ui-ktx:2.3.0-alpha04"