I am using jetpack navigation graph in my android project. Normally to navigate one to another fragment we connect a link between them in nav graph and call like this

 findNavController().navigate(R.id.action_navigation_login_to_navigation_send_code)

But We can call the fragment this way as well without creating the link.

 findNavController().navigate(R.id.navigation_send_code)

What is the basic difference? In my sense, both do the same work.

1

There are 1 best solutions below

4
On

Both versions back to the same navController navigate() function that takes in an integer resource id whether it's a fragment id or an action id.

Navigate to a destination from the current navigation graph. This supports both navigating via an {@link NavDestination#getAction(int) action} and directly navigating to a destination.

Internally it calls this navigate() version where it examines whether it's an action id or not.

If it's an action id, then it gets the destination id from it; if not an action id it consider it as a destination id and continue on; notice the comments in below:

@IdRes int destId = resId;
final NavAction navAction = currentNode.getAction(resId);
Bundle combinedArgs = null;
if (navAction != null) { // here the destId is an action id
    if (navOptions == null) {
        navOptions = navAction.getNavOptions();
    }
    destId = navAction.getDestinationId(); // resets the destId to the destination id
    Bundle navActionArgs = navAction.getDefaultArguments();
    if (navActionArgs != null) {
        combinedArgs = new Bundle();
        combinedArgs.putAll(navActionArgs);
    }
}

// Now destId is the destination fragment id.. continue on...

So, technically no difference, but adding an action id adds an extra step of getting the fragment id which is nothing in terms of scalable apps.

The other difference, that if you put an actionId instead of a fragment id, you'd have an extra feature of navOptions that can be returned from the navGraph like adding enter/exit animation.