Communicating Data Between Fragments: Using setFragmentResultListener

Enes Karpuzoglu
LCW Digital
Published in
2 min readOct 25, 2023

When developing Android applications, communicating data between fragments is a common scenario. The Fragment Result API, introduced in the AndroidX library with Fragment 1.3.0-alpha01, provides a powerful and straightforward solution for such situations. In this article, we’ll explore how to use the setFragmentResultListener method to facilitate data communication between fragments.

What is Fragment Result API?

The Fragment Result API is introduced in the AndroidX library starting from Fragment 1.3.0-alpha01. This API is used to transmit and listen for results between fragments, especially when you want to send data from one fragment to another.

Using setFragmentResultListener

The setFragmentResultListener method is used to communicate data between the sending and receiving fragments. Here's how you can use it:

In this code snippet, the setFragmentResultListener method is used to create a listener that listens for results with the key "requestKey". When results are received, the listener processes them and retrieves the data using the "dataKey" key.

In this code snippet, the setFragmentResult method is used to create a data bundle with a key "requestKey" and send it to the Receiving Fragment.

Conclusion

The Fragment Result API and the setFragmentResultListener method are powerful tools for facilitating data communication between fragments. This method allows for reliable and straightforward data exchange between fragments. By using this method, you can make your Android applications more modular and easier to maintain when communicating between fragments.

In this article, we’ve learned how to use the setFragmentResultListener method to facilitate data communication between fragments. By applying this technique, you can achieve easy and reliable data communication between fragments in your Android applications.

--

--