Reputation: 17613
I've been using DialogFragment
to handle Dialogs on an app.
I've read this which gives some examples about how to use it, but it always uses things like:
((FragmentAlertDialog)getActivity()).doPositiveClick();
((FragmentAlertDialog)getActivity()).doNegativeClick();
I don't really like this implementation as it obliges a cast to a pre-known Activity so it's not very robust.
I also know that passing and storing a callback inside the FragmentDialog
isn't a good option because if it references an Activity, after rotation for example, that activity could have been destroyed... and the callback is not updated.
Also updating the callback when an activity passes onResume
is also not a very viable option, as it had to know which Dialog is being shown and set a callback related to it making the logic a bit tricky on larger apps.
So what implementation do you suggest to avoid casts while retaining always the most up-to-date callback?
Upvotes: 2
Views: 414
Reputation: 7817
You've enumerated the reasons why callbacks can't be used, very eloquently. Unfortunately, I think the cast (or something similar) is unavoidable. The whole paradigm is rather awkward, frankly.
You could use an interface, if you plan to share a dialog fragment between multiple activities.
((IXyzDialogHost)GetActivity())->onSomethingHappened()
There's something to be said for that approach, I suppose. I can't say I've used that approach myself, personally, but thinking about it, I might be tempted to do so moving forward. At least you can enforce a contract on the calling Activity with an appropriate static DialogFragment.Create method, which deals with the setting of the bundle the fragment manager transaction, and other unpleasantries:
class XyzDialogFragment {
{
public static DialogFragment Create(IXyzDialogHost activity, ...)
{
...
}
}
But there's still a cast.
Upvotes: 1