11

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?

Halvtysk
  • 257
  • 2
  • 10
  • If I get you right, you want to be able to navigate to a **particular** fragment from **any** fragment with NavigationComponent, right? – Taslim Oseni Sep 16 '20 at 12:54

1 Answers1

19

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

Xid
  • 4,578
  • 2
  • 13
  • 35
  • 2
    Wow, that was really hidden in the documentation/UI of Android Studio (or I am just really blind). I guess now is the time I remove all the hardwired generic dialogs I have implemented, even though I apparently didn't have to... Thanks for pointing it out! – Halvtysk Sep 17 '20 at 06:01
  • 1
    Stackoverflow is always a better documentation than developer.android.com – Serdar Samancıoğlu Sep 24 '21 at 11:38