Guide to Communicating Between Fragments

Guide to Android: Part 2

Achintha Isuru
2 min readAug 29, 2023
Photo by Denny Müller on Unsplash

Welcome to another edition of the Guide to Android series. In this article, we will delve into the process of communicating (passing data) between Fragments.

Unlike other articles, we won’t delve into background information here; let’s jump straight into coding.

https://giphy.com/

Steps to Communicate Between Fragments

To facilitate communication between fragments, the recommended approach is to utilize the Activity in which the fragments reside. The process is illustrated in the diagram below.

As depicted above, the Activity needs to be wrapped with an interface containing the `sendData` method. This method will be invoked from the first fragment to transmit the required data to the second fragment.

1. Create the interface

interface SendMessage {
fun sendData(message: String)
}

2. Extend the relevant activity with the interface.

class MainActivity : AppCompatActivity(), FirstFragment.SendMessage {
...
}

3. Invoke the sendData method from the first fragment.

firstFragmentButton.setOnClickListener {
mainActivity.sendData(firstFragmentEditText.text.toString())
}

4. Implement the `sendData` method in the Activity.

Ensure the `supportFragmentManager` is employed to locate the second fragment; otherwise, there’s a high likelihood of encountering unexpected errors.

override fun sendData(message: String) {
val secondFragment: SecondFragment = supportFragmentManager.findFragmentById(R.id.secondFragment) as SecondFragment
secondFragment.setSecondFragmentText(message);
}

5. Within the second fragment, you can design a method to capture the sent data and utilise it as needed.

fun setSecondFragmentText(message: String) {
secondFragmentText.text = message;
}

That’s all there is to it!

https://giphy.com/

The complete code can be accessed from this GitHub repository.

Conclusion

This article comprehensively covered the method for communicating between fragments in Android. If you found this article helpful, please don’t hesitate to share it with your friends and colleagues.

Thank you, and HAPPY CODING! 👩‍💻🧑🏽‍💻👨🏿‍💻

Thank you for reading until the end. Please consider following the writer and this publication. Visit Stackademic to find out more about how we are democratizing free programming education around the world.

--

--