Fragment communication – Android


Passing data between two fragments in Android.

Fragment communication is an essential topic in Android. In this post, we are going to learn how to establish communication between fragments.

We are going to create an Android project. In this project, we will have one activity. The activity will have two fragments, FragmentA and FragmentB.

In FragmentA, there will be an EditText and a Button.

In FragmentB, there will be only a TextView.

Clicking on the Button in FragmentA will show the EditText data in FragmentB’s TextView.


Always remember, a fragment can’t communicate with another fragment directly. Two fragments can communicate with one another through an Activity.

And to transfer data from one fragment to another we have to establish a connection. This connection can be established by an Interface.

Now that you have the basic idea of how to do it, let’s see a practical example of it by creating a project.

Go to Android Studio and create a new project and create two fragment classes. and

We also need two layouts for both of our fragments.

Let’s create the FragmentOne.

This is the layout of our FragmentOne.

fragment_one.xml – 

Similarly, create and its layout file.

And the layout of our FragmentTwo.

fragment_two.xml :

We also have to update your activity layout.

activity_main.xml – 

Now get reference to the views. EditText, Button, and the TextView.

Update your Fragment class code to match ours.

What we are doing is, we are setting a click listener on the button in FragmentOne. When a user types something in the EditText and clicks on the button, the text shows in the TextView of FragmentTwo.

As you already know, to do this we have to establish a connection between the two fragments. We can establish a connection with an interface.

So create an interface and name it Communicate.

If you don’t know how to create an interface, Go to File – New – Java Class. Select Interface from the drop-down menu of Kind.

After creating the interface, we need to specify one abstract method that takes a single String parameter.

Now we have to pass the EditText value in FragmentOne to myData(String data). Update your class.

This is our final code for FragmentOne.

We also need to add a method in class to set the value to the TextView.

Update your class with the below code.

As you know the fragments can communicate with each other through an activity. So our MainActivity should implement Communicate interface.

Below is the complete code for our class.

That’s all. Now run the project and type something in the EditText field and hit the button.

More android tutorials – 

Toast message and positioning – Android

YouTube search from your App – Android

If you have any doubts or query or suggestions related to this post, please don’t hesitate to comment below in the comment section.


You May Also Like

1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *