How to pass a function as an argument to a destination fragment - Android Navigation Component

Viewed 827

I have a class that extends DialogFragment that I'd like to use as a destination in my navigation graph so that I can open it like I would any other fragment. I'd like to pass functions as arguments to my DialogFragment class to be used in the positive and negative button listeners. In this case they would be functions from the calling Fragment.

So, is it possible to pass functions as arguments to a Navigation Component destination, or is there another way to go about doing this. Does the DialogFragment need its own ViewModel?

1 Answers

The way I ended up doing this was by having a shared ViewModel, as @CommonsWare suggested.

The ViewModel is setup like this:

class ViewModel(application: Application) : AndroidViewModel(application) { }

and it is instantiated like this, using requireActivity() in both fragments that use it to make sure that it acts as a singleton, since those fragments share a parent activity.

val viewModel = ViewModelProvider(requireActivity()).get(ViewModel::class.java)
Related