我正在使用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())
这里是导航图中的代码。
<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)
}