简体   繁体   中英

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

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM