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.
Fragment CommunicationTo have a sharing of data between Fragments, either you can use a shared ViewModel that is shared between all the Fragments or you can make an Interface and then use this interface to communicate between fragments.
Fragments represent a behavior or portion of UI in an Activity. Fragments are mostly used in tablets to divide screen and utilize screen space in efficient way. With Android 4.2 nested fragments are introduced, with which now you can embed fragments inside fragments.
To properly react to user events, or to share state information, you often need to have channels of communication between an activity and its fragments or between two or more fragments. To keep fragments self-contained, you should not have fragments communicate directly with other fragments or with its host activity.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With