首页 > 解决方案 > 配置更改后,Android 导航组件重置为开始目的地

问题描述

我正在使用 Android 导航组件,如果我在第二个片段中,我有一个包含三个片段的活动,并且旋转屏幕强制活动重新启动导航返回到起始目的地。

活动重新启动时,navhostFragment 不应该保留图形的状态吗?

还是这里的默认行为发生了什么?

即使添加“有效”,我也不想添加以下内容

 android:configChanges="orientation|screenSize|screenLayout|keyboardHidden"

因为我不想自己处理方向变化,我希望它被系统正常处理并且仍然保留导航状态

如果有帮助,我将提供我的一些代码

在我使用 navController.setGraph() 的活动中,我可以像这样将数据传递到起始目的地

 navController = Navigation.findNavController(
        this,
        R.id.nav_host_fragment
    )
 setSupportActionBar(findViewById(R.id.toolbar))
 appBarConfiguration = AppBarConfiguration.Builder(navController.graph).build()
 supportActionBar?.setDisplayHomeAsUpEnabled(true)

 intent.putExtra("EXTRA_KEY","some_data")
 navController.setGraph(R.navigation.nav_graph,intent.extras)

我使用这个从一个片段导航到另一个片段

navController.navigate(FirstFragmentDirections.actionFirstFragmentToSecondFragment())

这是 nav_graph 中的代码

<fragment
    android:id="@+id/FirstFragment"
    android:name="com.example.app.presentation.ui.FirstFragment"
    android:label="FirstFragment" >
    <action
        android:id="@+id/action_FirstFragment_to_secondFragment"
        app:destination="@id/secondFragment"
        app:enterAnim="@anim/enter_from_right"
        app:exitAnim="@anim/exit_to_left"
        app:popEnterAnim="@anim/enter_from_left"
        app:popExitAnim="@anim/exit_to_right"
        />
</fragment>
<fragment
    android:id="@+id/secondFragment"
    android:name="com.example.app.presentation.ui.secondFragment"
    android:label="secondFragment"
    tools:layout="@layout/fragment_second" />

感谢您提供任何帮助谢谢

标签: androidandroid-architecture-componentsandroid-jetpackandroid-architecture-navigationonconfigurationchanged

解决方案


您通常永远不需要调用setGraph()自己,但是在这种特殊情况下您可以像这样解决它(实际上它仍然可以按您的预期工作,因为 NavController / Navigator 会在配置更改时正确恢复状态并自动处理死亡):

if (savedInstanceState == null) {
    navController.setGraph(R.navigation.nav_graph,intent.extras)
}

推荐阅读