Search code examples
androidandroid-jetpackandroid-jetpack-navigation

What is the use of the action of Jetpack navigation?


I am new to programming and I am confused about the action of android jetpack navigation, Since we can navigate directly to any other destination from any destination, why do we need action?

If I have nav_graph.xml file like below. I can navigate to ProfileFragment from MainFragment by call findNavController().navigate(R.id.profile_fragment), so why do we need acion? What's the point of it's existence?

Can someone show me a simple example, it would be greatly appreciated.

<navigation xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/nav_graph"
        app:startDestination="@id/main_fragment">
    <fragment
            android:id="@+id/main_fragment"
            android:name="com.google.android.conditionalnav.MainFragment"
            android:label="fragment_main"
            tools:layout="@layout/fragment_main">
        <action
                android:id="@+id/navigate_to_profile_fragment"
                app:destination="@id/profile_fragment"/>
    </fragment>
    <fragment
            android:id="@+id/profile_fragment"
            android:name="com.google.android.conditionalnav.ProfileFragment"
            android:label="fragment_profile"
            tools:layout="@layout/fragment_profile"/>
</navigation>

Solution

    1. It is best to use action because it's safe to navigate with any runtime navigation error using navigation-safe-args plugin.

    2. Safe Args to pass data with type safety

    3. It show graphical linking representation of screens in design tab.

    An action is a logical connection between destinations. Actions are represented in the navigation graph as arrows. Actions usually connect one destination to another, though you can also create global actions that take you to a specific destination from anywhere in your app.

    With actions, you're representing the different paths that users can take through your app. Note that to actually navigate to destinations, you still need to write the code to perform the navigation. This is covered in the Navigate to a destination section later in this topic.

    Reference: Navigation Actions