使用導覽動作和片段

您可以使用導覽動作,在片段之間建立連結。觸發導覽動作時,使用者會從一個目的地前往另一個目的地。本指南將介紹何謂動作,並說明如何建立及使用動作。

總覽

每個動作都具有專屬 ID,可包含目的地等額外屬性。目的地會定義使用者觸發動作時,應用程式會將他們導向哪個畫面。動作也可以使用引數,在不同目的地之間傳遞資料。

  • Safe Args:透過動作,您可以將資源 ID 替換為 Safe Args 產生的作業,增添編譯時的安全性。
  • 動畫:您也可以為目的地之間的轉場加上動畫效果。詳情請參閱這篇文章

範例

請使用 <action> 標記,在導覽圖 XML 檔案中定義動作。下列程式碼片段會實作動作,代表從 FragmentA 轉換到 FragmentB

<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 則是任何特定片段外的全域動作。這表示您可以在 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>