naokiokada
naokiokada

Reputation: 151

Android Jetpack Navigation: How to get fragment instance of destination in OnNavigatedListener?

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
        }
    }
}

UPDATE: The scenario

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()

Upvotes: 15

Views: 4868

Answers (1)

jpalvarezl
jpalvarezl

Reputation: 325

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.

Upvotes: 1

Related Questions