Communication between Activity and Fragments

Android how to communicate between Activity and Fragment

Often we need to communicate between Activity and Fragments. Fragment to Activity communication is done through interfaces.

In order to create a communication flow between Fragment and Activity you can define an interface in the Fragment class. This interface should be implemented in the Activity class. In Fragment the interface is initialised in onAttach. Once it is initialised the interface function can be called to send message to Activity via interface call.

Fragment To Activity Communication

1> Define interface in Fragment class

2> Initialise Interface in onAttach

3> Implement Interface method in Activity

4> Call interface method in Fragment.

Activity To Fragment Communication

We saw how to implement interface method to communicate from fragment to activity. Now if there is a need to communicate from activity to fragment then we need to use fragment manager to call fragment method directly.

FragmentManager is used to get fragments attached to the activity. Once you get the reference to the fragment then it can be cast to call the method directly. Let’s see an example of how to call fragment method from the activity class.

1> Create method in Fragment class

2> Call Fragment method from Activity class

If the fragment is defined in the layout then findFragmentById is used to find respective fragment.

Leave a Reply

%d bloggers like this: