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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With