Communication B/W Activity And Fragment Using Interfaces | Android Tutorial

Anas Iqbal
3 min readAug 14, 2020

--

Hello, In this post I’ll show you an easy and simple way to communicate between activity and fragment using interfaces, yeah that’s right. If you have already found a way to do it then that’s great, but if you are still looking for a way to do it then I guess the post will help, so let’s get started!

Below you can see a basic layout with for the first part, It’s an activity with a fragment inside, now the goal is to click on the button shown in the activity and do something on the fragment when it’s clicked.

Ok so now, we will make an interface inside activity and it will contain an abstract method, I’ll just share the snippets of relevant code, but you can find the complete project on the Github (link at the end of this post).

As you can see I just created an interface inside activity, it has an abstract method right now it doesn’t take any parameters but you can also add parameters and if you would like to send some data from activity to fragment. Now we will implement an interface on our fragment class.

Now, I have implemented an interface in fragment class ,so now In my MainActivity class I can use an instance of fragment and call the function doSomething(). Now I am just gonna add a button on MainActivity and call the interface method when the button is clicked and it should change the text in fragment.

Perfect! Now we will do the same but this time we will do something on activity when there is any event on fragment, so I’ll just create another fragment and declare an interface inside it.

In the code above you can see I just created an interface and then declared a variable of interface inside fragment and onAttach() method I am type casting the activity into the interface so we can trigger the interface method on fragment button click and then we will implement the interface in our activity class and do something on our activity when the button inside fragment is clicked.

Let’s check it out.

I guess that’s it, I just showed you a simple way to communicate between activity and fragment using interfaces, but sure you can use this same approach to communicate between adapter and activity or fragment. I hope it will help you in some way :)

Project link : https://github.com/anas-iqbal/activity-fragment-communication-interfaces

--

--