Fragment Communication

To make sure fragment is available for reuse, fragments should be written self contained way i.e it should handled its own layout and behaviour.

But for this to happen fragment would need a channel of communicate to share user events, or share information with other components. Based on the use case there are 2 recommended ways:
  • Using ViewModel and LiveData
  • Using Fragment Result API
We are going learn about #2 in this article. We will revisit #1 when we learn about ViewModel and Live Data (part of Architectural Components).

Using Fragment Result

Majorly used to send one-time value between two fragments, or between a fragment or with host activity.

Internals:

FragmentManager manages the sending and receiving the fragment result. It implements FragmentResultOwner which makes FragmentManager as a central store for fragment results.

Communication between 2 fragments with same host activity

Code for result listener:



Code for result setter:


Communication between parent and child fragment:

Code for result listener:


Code for result setter:


Communication between parent activity and fragment:

Code for result listener:



Code for result setter:



To make sure these works correctly same key should be shared between observer and owner and these methods should be called on same FragmentManager.

A few points to note:

  • Same key should be shared with observer and owner both calling the methods of same FragmentManager.
  • There can be only one listener to the fragment result
  • Listener gets the callback only if it is at least STARTED state. Till then the results are stored in FragmentManager
  • Once the result is fire, the result stored in FragmentManager is cleared.
  • Fragment must of attached so that setFragmentResultListener() or setFragmentResult() can be called.

Resources

https://developer.android.com/guide/fragments/communicate

Comments

Popular posts from this blog

Fragment Lifecycle

AndroidManifest

Activity Lifecycle