Reputation: 60244
I'm fighting couple of days with a such simple think like receiving back a data from a DialogFragment
. First I tried to make a DialogFragment
as a nested class, but it happened it fails on orientation change. Then I decided to user interfaces
passing a listener
to a DialogFragment
, but here is a problem on how to persist the listener
after orientation change
. Then someone from here suggested to use setTargetFragment()
, but it is also doesn't work because of a known issue.
It is such a common task, how you guys get data back from DialogFragment
s.
Upvotes: 2
Views: 2602
Reputation: 39255
Using interfaces, and hooking up in onAttach(Activity)
definitely works, and the example given by Google suggest to communicate between components this way, but there is definitely a better way to do things. Square came out with a nice solution that you can find here:
http://corner.squareup.com/2012/07/otto.html
It's an event bus that you can register with to receive event notifications, and really decouples your component communication code.
To register for an event from your DialogFragment (say, you've got the data you need and you're about to dismiss, so your event notifies all interested parties with the data) all you'd do in your Activity is:
bus.register(this);
Then in the same Activity you'd have something like:
@Subscribe
public void dataChanged(DataChangedEvent event) {
// TODO React to data.
}
Then the DialogFragment, would only need to call something like:
bus.post(new DataChangedEvent(/*your data here*/));
and your Activity would be notified. No coupling of your Activities to your Fragments, and no keeping track of listeners.
Upvotes: 5
Reputation: 31503
Whenever you attach the logic activity to the fragment manager be sure to use the additional parameter for tag. Then, in onCreate
of your DialogFragment just call getFragmentManager().findFragmentByTag("parent fragment");
to get a reference to the parent.
Upvotes: 0
Reputation: 786
Using interfaces is definitely the best way.
In your DialogFragment
, register the listener in onAttach(Activity)
and you will be able to receive your callback even after an orientation change.
Upvotes: 3