The Android developers site has a great article on how to use interfaces to communicate between:
- A
Fragmentand its hostingActivity - Two
Fragments hosted by the sameActivity
I am struggling to apply this concept to nested fragments. In particular, getActivity() or Fragment#onAttach(Activity) tell you what Activity is hosting a Fragment.
What is the equivalent in case of nested fragments? How does a “child” Fragment know what “parent” Fragment it is included in? And without knowing this, how can a child Fragment pass events up to its parent Fragment?
An obvious way is to broadcast intents from the child Fragment and have the parent Fragment listen for the broadcast, but I’d rather use the interface-based approach.
It turns out there is a getParentFragment() method introduced to cater to nested fragments. It is available on
android.app.Fragmentfrom API 17, but can be used on older versions usingandroid.support.v4.app.Fragment.I can’t believe I overlooked this API!
EDIT:
I came across this gist that makes this process of figuring out the parent component (whether
FragmentorActivity) easy, elegant and safe!