Reputation: 10672
The Android developers site has a great article on how to use interfaces to communicate between:
Fragment
and its hosting Activity
Fragment
s hosted by the same Activity
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.
Upvotes: 39
Views: 9247
Reputation: 10672
It turns out there is a getParentFragment() method introduced to cater to nested fragments. It is available on android.app.Fragment
from API 17, but can be used on older versions using android.support.v4.app.Fragment
.
I can't believe I overlooked this API!
I came across this gist that makes this process of figuring out the parent component (whether Fragment
or Activity
) easy, elegant and safe!
Upvotes: 60