Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
280 views
in Technique[技术] by (71.8m points)

android - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...