Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android best practices for Fragment to Activity communications

I am new to Android Fragment and trying to learn Fragment to Activity communications. What is the better approach(best practice) in Android for Fragment to Activity communication?

Lets say I have FragmentA and ActivityA. After my screen popups FragmentA, I would like to perform somemethod(probably UI related) in ActivityA

Here are two(pattern) possible Solutions:

  1. In FragmentA getActivity and cast the Activity to ActivityA and then call somemethod.
  2. In FragmentA create an interface callback and then implement that callback in ActivityA. Then on the callback, call somemethod.

Which pattern is more common/perfer in Android development and why. Or do you have an even better way to communicate from fragment to activity in Android to share with me?

Any comments, opinions, and suggestions is highly appreciated and welcome. ^^ .

like image 857
xiaowoo Avatar asked Sep 12 '14 18:09

xiaowoo


People also ask

What is the best way for two fragments to communicate?

The Fragment library provides two options for communication: a shared ViewModel and the Fragment Result API. The recommended option depends on the use case. To share persistent data with any custom APIs, you should use a ViewModel .

How do you communicate from fragment to activity?

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.

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 can two fragments communicate Android?

We can communicate within fragments using the ViewModel. We can also communicate between fragments using Interface.


1 Answers

The second solution is the preferred one, because it allows your fragment to be more independent of its hosting activity.

If in the future you decide to put your fragment on a different activity, there are no changes needed on the fragment, and you will only need to implement the interface on your activity.

I'll add a third solution which is using an event bus (Otto for instance), which also works, although some might argue that it makes your code a little less readable.

like image 131
Julian Suarez Avatar answered Nov 15 '22 10:11

Julian Suarez