Learn how Fragments communicate with each other via Activity

Now that you have two Fragments – a ListFragment and a Detail Fragment, its time for you to call the Detail Fragment from ListFragment.

Let’s understand the Fragment Communication concepts.

Suppose you have a List FragmentA which displays a List of Items. And on click of an item in the list you want to display another FragmentB.

Sounds simple ! Call the FragmentB from the FragmentA. But the catch here is that we want the two Fragments to be unaware of each other. So that they can be used with any Activity independently.

The idea here is that Fragment A will invoke Fragment B via the Activity class. And in order to decouple Fragment A and the Activity we will introduce an Interface.

Confused ? Ok, let me share an example to make this clear.

Here is some sample code

MyActivityClass implements FragmentAInterface{
callFragmentB(){
//Code to call FragmentB
}
}

FragmentA{
FragmentAInterface fragmentAInterface;

interface FragmentAInterface{
callFragmentB();
}

onItemClick(){
fragmentAInterface.callFragmentB();
}

onAttach(Activity activity){
fragmentAInterface = (FragmentAInterface) activity;
}
}
FragmentB{

}

Now what is going on here?

Understanding the Code

The FragmentA defines an interface FragmentAInterface which has one method callFragmentB.

Your Activity class MyActivityClass implements this interface and defines callFragmentB method. In which it calls FragmentB.

Now when a user clicks on an item in FragmentA the onItemClick method is called. We want this method to trigger the MyActivityClass -> callFragmentB method.

So what we do is we create a reference of the FragmentAInterface “fragmentAInterface” and assign it the Activity in onAttach method. Remember the Fragment Lifecycle ?

So this is how it works. And you can use this principle to implement such functionality.

Source Code available here

Author: androidsmartly

I am a Tech Enthusiast who likes to work on new Ideas. Sharing knowledge on Android, Marketing, Startups and More.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s