Search code examples
androidandroid-fragmentsandroid-dialogfragmentandroid-mvp

How can I pass a listener from a Fragment to a DialogFragment?


I'm currently working in a single activity application that is using fragments for each screen. I'm also using MVP design pattern.

Context

  • I have a Fragment (Fragment-A) in which I have a List of Items. This Fragment handles the actions for each of the items. Because it has access to the presenter.
  • I have a DialogFragment (Fragment-B) in which you can fill some checkboxes and complete an action (This is action is handled in the Fragment-A which implements an interface for this)
  • I'm using a bundle to create DialogFragment. (I can't pass the listener as an argument)

What I want?

How can I pass Fragment-A as a Listener to the DialogFragment (Fragment-B), so I can call the actions from the DialogFragment?


Solution

  • Assuming your DialogFragment is a child fragment of the other Fragment (you're passing in getChildFragmentManager() to show()) as it should be, then your FragmentA will get a callback to onAttachFragment():

    Called when a fragment is attached as a child of this fragment.

    This gives you a reference to the child DialogFragment, where you can then set any listener you want.