I am working on an android application with many dialogs, all of which extend a custom class called "DialogFragmentBase" which extends the library's "DialogFragment". All activities use the show() method overridden in DialogFragmentBase.
I want to prevent showing the dialogs if the parent activity is backgrounded (as in receiving a phone call) since that results in the illegalStatEexception, but at the same time I don't want to guard every show() call in the application with:
if(getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED))
So I wanted to do something like this in the DialogFragmentBase:
@Override
public void show(FragmentManager manager, String tag){
List<Fragment> fragments = manager.getFragments();
if(fragments != null && fragments.size() > 0){
FragmentActivity activity = fragments.get(fragments.size()-1).getActivity();
if(activity != null && activity.getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED)){
super.show(manager, tag);
}
}
}
So my question is: Is accessing the previous fragment like that considered a bad practice? It does work...but I remember reading somewhere that fragments shouldn't intercommunicate. If it is indeed a bad practice, what would be a better solution that can be implemented in the DialogFragmentBase (to avoid adding guards everywhere).
Note: I tried the onSaveInstanceState solution described here, but since the DialogFragment hasn't been shown yet, the onSaveInstanceState isn't called for it at that point. Also getActivity() returns null since onAttach hasn't been called yet at that point.
Thanks!
The support library FragmentManager
has an isStateSaved()
method. Depending on exactly what your requirements are, you could leverage this to check if it is "safe" to show your dialogs:
@Override
public void show(FragmentManager manager, String tag) {
if (!manager.isStateSaved()) {
super.show(manager, tag);
}
}
Note that the above implementation is relatively similar to using commitAllowingStateLoss()
, in that you'll silently fail to show your dialog in certain cases. But perhaps that is fine for your requirements.