I'm using Jetpack Navigation Components in android development (One activity, many fragments).
I want to get fragment instance of destination in OnNavigatedListener
like below.
Is it possible?
class MainActivity : AppCompatActivity() {
private lateinit var navController: NavController
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(this, R.layout.activity_main)
navController = Navigation.findNavController(this, R.id.nav_host_fragment)
navController.addOnNavigatedListener { controller, destination ->
// Here
}
}
}
I want to get a fragment's property (or returned value from method) in activity on navigated each time.
For example,
val fragment = getFragmentInstanceFromDestination()
myActionBar.visible = fragment.getActionBarVisible()
popUpTo and popUpToInclusive For example, if your app has an initial login flow, once a user has logged in, you should pop all of the login-related destinations off of the back stack so that the Back button doesn't take users back into the login flow.
In its own words, AndroidX Navigation is “a framework for navigating between 'destinations' within an Android application that provides a consistent API whether destinations are implemented as Fragments, Activities, or other components.”
If you are using the 1.0.0-alpha07
version, it used to be possible to do something like this:
(destination as? FragmentNavigator.Destination)?.let { destinationClass ->
val isNewFullscreen = destinationClass.fragmentClass.superclass == FullScreenFragment::class.java
//... adjust paddings and hide action bar, etc.
This is the approach I took for a single Activity app having two Fragment super classes, one of them is FullScreenFragment (the one you can see being used in the example), which hides action bar and navigation bar and also, NavigationFragment (the name is confusing, but this one shows the navigation bar and action bar).
The problem with this, is that you also need to adjust the padding of your default navigation fragment, as for FullScreenFragments it would occupy the entirety of the screen whereas NavigationFragment should account both for the action and navigation bar.
Now with the new 1.0.0-alpha08
the FragmentNavigatio.Destination.fragmentClass
is no longer available, so I am still thinking how to solve this. I am considering using destination.id == R.id.someFullScreenFragment
, it is definitely less hacky than what I have in place at the moment, but I would have to keep track of a list of ids.
Either way, it is not possible, as far as I know, to get the instance of the Fragment itself, the best you can do is infer the destination and let your single activity orchestrate views accordingly.
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