【问题标题】:Android navigation component resets to start destination after configuration change配置更改后,Android 导航组件重置为开始目的地
【发布时间】:2020-06-02 10:45:12
【问题描述】:

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

在activity重启时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" />

感谢您的帮助,谢谢

【问题讨论】:

    标签: android android-architecture-components android-jetpack android-architecture-navigation onconfigurationchanged


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢,我试过了,它解决了问题。所以在 onCreate 中设置图表是让它重置的原因。非常感谢
    • 这是什么intent.extras?我们在里面传递了什么
    • 我认为传递给初始目的地的参数
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-02
    • 1970-01-01
    • 1970-01-01
    • 2011-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多