Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Navigation Component - navigate from "anywhere"/base fragment?

I'm working on an app that has a quirky gimmick to open a specific fragment when the device is rotated. Before implementing android's navigation component, all that was needed was a reference to the current activity, and a manual fragment transaction could be performed on top of whatever was shown to the user at that particular moment.

But after moving to navigation component, I find it hard to implement generic stuff like the above example or (for example) how to display a simple dialog from a base fragment class.

Is there a proven way to write this kind of logic?

"SpecificFragment.kt" extends "BaseFragment.kt"

BaseFragment.kt could host all generic logic to start fragment. The common fragment logic still exists in the BaseFragment, but BaseFragment (an abstract class) is not in the nav-graph (nor should it be (?). Hence, I cannot call "BaseFragmentDirections.actionXXXX()" from any fragment.

How is this supposed to be written?

like image 659
Mattias Zippert Avatar asked Mar 09 '26 08:03

Mattias Zippert


1 Answers

What you are looking to implement is a global action.

Create a global action in your navigation graph. Like so:

<?xml version="1.0" encoding="utf-8"?>
<navigation 
    android:id="@+id/navigationGraph"
    ...>

  ...

  <action android:id="@+id/moveToSpecificFragment"
          app:destination="@id/specificFragment"/>

</navigation>

Use it in your base fragment:

findNavController().navigate(NavigationGraphDirections.moveToSpecificFragment())

Note: The Directions class for your global actions will correspond to the id of your navigation graph

like image 85
Xid Avatar answered Mar 11 '26 07:03

Xid