android - 配置更改后,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" />
感谢您提供任何帮助谢谢
解决方案
您通常永远不需要调用setGraph()
自己,但是在这种特殊情况下您可以像这样解决它(实际上它仍然可以按您的预期工作,因为 NavController / Navigator 会在配置更改时正确恢复状态并自动处理死亡):
if (savedInstanceState == null) {
navController.setGraph(R.navigation.nav_graph,intent.extras)
}
推荐阅读
- c# - 不应该发生关于异步的编译器警告
- javascript - 如何在 JavaScript 中加入具有不同分隔符的数组?
- python - Python函数根据另一列填充nan值
- spreadjs - 在spreadjs中复制后如何为单元格中的双下划线文本添加内联样式
- regex - 如何跳过第一场比赛并将第二场比赛打印为 $1
- wix - 仅使用 .Net Core 的 Wix MSI Bootstrapper
- python-3.x - python - 如何在python中获取给定特定属性的父母和祖父母标签?
- php - PHP preg_replace RCE
- c++ - 当 Q_GADGET 结构位于单独的头文件中时,在 QML 中出现“未注册的数据类型”错误
- docker - Docker: Installing NVM onto Debian image, without restarting