Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why direct communication between fragments is not recommended?

while learning android fragments on developer.android.com it is specified that direct communication between two fragment is not recommended. I want to know what will be the consequences and the cases in which communication between two Fragments would fail?

like image 523
Chaitanya K Avatar asked Jul 20 '12 06:07

Chaitanya K


People also ask

Why two fragments should never communicate directly?

Two Fragments should never communicate directly. The reason for this is that Fragment s are fluid & dynamic UI components that may fade in and out of view. Only the hosting Activity is capable of determining if a Fragment is added to the UI or has been detached from it.

How do you communicate between fragments and activities?

To allow a Fragment to communicate up to its Activity, you can define an interface in the Fragment class and implement it within the Activity. The Fragment captures the interface implementation during its onAttach() lifecycle method and can then call the Interface methods to communicate with the Activity.

What are fragments in communication?

Sentences must contain at least one independent clause. In other words, sentences must (1) have a subject (someone or something doing action), (2) have a verb (action), and (3) convey a complete thought. Sentences that break one or more of these rules are called sentence fragments.


2 Answers

Well, with Fragments you aren't always sure if they will be alive and attached at the time of communication. Whether Fragments are attached and available or not might also depend on device layout or size. If you're absolutely sure that your Fragments will both be attached to your activity and available at the same time, then I suppose you can communicate directly.

Having said that, Fragments are meant to be logical, standalone units. From the docs:

You can think of a fragment as a modular section of an activity

It kind of breaks the model if the fragments are affecting each other directly.

Why not rather define an interface in your Activity and get Fragment A to call a method in the Activity? Then your Activity can check whether Fragment B is available and can then call the appropriate function in Fragment B.

Here is the docs suggestion

like image 139
Mike T Avatar answered Nov 15 '22 19:11

Mike T


A Fragment is just a UI component that does a little more than draw itself. In the scope of this question, its no different from a View.

So a very comparable question would be: why cannot two Views communicate with each other directly?

like image 20
Vikram Bodicherla Avatar answered Nov 15 '22 17:11

Vikram Bodicherla