我正在使用Android导航组件,有一个包含三个片段的活动。如果我在第二个片段并旋转屏幕以强制重启活动,则导航返回到起始目的地。navhostFragment是否应该保留图形的状态当活动重新启动时?这里发生的是默认行为吗?我不想添加以下内容,即使添加它也可以“工作”。
因为我不想自己处理方向变化,我希望它能被系统正常处理并仍保留导航状态。
如果有需要,我会提供我的一些代码。
在活动中,我使用navController.setGraph(),这样我就可以像这样将数据传递到起始目的地。
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" />
非常感谢您的帮助。
Activity.onCreate
甚至Fragment.onCreate
中进行(使用onCreateView
会导致错误,所以你也必须在onCreate
中添加NavhostFragment,非常hacky,我有一个例子)。 - EpicPandaForce