Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inter-fragment communication applied to Nested Fragments?

The Android developers site has a great article on how to use interfaces to communicate between:

  1. A Fragment and its hosting Activity
  2. Two Fragments 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.

like image 932
curioustechizen Avatar asked Feb 12 '13 11:02

curioustechizen


People also ask

What is inter fragment communication?

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.

What are nested 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.

Why fragments Cannot communicate with another fragment directly?

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.


1 Answers

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!

EDIT:

I came across this gist that makes this process of figuring out the parent component (whether Fragment or Activity) easy, elegant and safe!

like image 173
curioustechizen Avatar answered Sep 19 '22 19:09

curioustechizen