使用导航操作和 Fragment

您可以使用导航操作在 fragment 之间构建连接。调用导航操作会将用户从一个目的地转到另一个目的地。本指南介绍了什么是操作,以及如何创建和使用操作。

概览

每项操作都有唯一 ID,并且可以包含其他属性,例如目的地。目的地定义了用户触发相关操作时应用会转到的屏幕。该操作还可以使用参数将数据从一个目的地传输到另一个目的地。

示例

使用 <action> 标记在导航图 XML 文件中定义操作。以下代码段会实现表示从 FragmentAFragmentB 的过渡的操作。

<fragment
    android:id="@+id/fragmentA"
    android:name="com.example.FragmentA">
    <action
        android:id="@+id/action_fragmentA_to_fragmentB"
        app:destination="@id/fragmentB" />
</fragment>

如需使用此操作进行导航,请调用 NavController.navigate() 并向其传递操作的 id

navController.navigate(R.id.action_fragmentA_to_fragmentB)

全局操作

您可以使用全局操作从任意位置导航到目的地。

对于应用中可通过多个路径访问的任何目的地,请定义导航到该目的地的相应全局操作。

请参考以下示例。results_winnergame_over 目的地都需要弹出到主目的地。action_pop_out_of_game 操作提供了执行此操作的功能;action_pop_out_of_game 是任何特定 fragment 之外的全局操作。这意味着您可以在 in_game_nav_graph 中的任何位置引用和调用它。

<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   android:id="@+id/in_game_nav_graph"
   app:startDestination="@id/in_game">

   <!-- Action back to destination which launched into this in_game_nav_graph -->
   <action android:id="@+id/action_pop_out_of_game"
                       app:popUpTo="@id/in_game_nav_graph"
                       app:popUpToInclusive="true" />

   <fragment
       android:id="@+id/in_game"
       android:name="com.example.android.gamemodule.InGame"
       android:label="Game">
       <action
           android:id="@+id/action_in_game_to_resultsWinner"
           app:destination="@id/results_winner" />
       <action
           android:id="@+id/action_in_game_to_gameOver"
           app:destination="@id/game_over" />
   </fragment>

   <fragment
       android:id="@+id/results_winner"
       android:name="com.example.android.gamemodule.ResultsWinner" />

   <fragment
       android:id="@+id/game_over"
       android:name="com.example.android.gamemodule.GameOver"
       android:label="fragment_game_over"
       tools:layout="@layout/fragment_game_over" />

</navigation>