탐색 작업 및 프래그먼트 사용

탐색 작업을 사용하여 프래그먼트 간에 연결을 빌드할 수 있습니다. 탐색 작업을 호출하면 사용자가 한 대상에서 다른 대상으로 이동합니다. 이 가이드에서는 작업이 무엇인지 설명하고 작업을 만들고 사용하는 방법을 보여줍니다.

개요

각 작업에는 고유 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>