Communicate between 2 Fragments in a Activity

Tram Ho

Surely Android developers interviewed often have questions such as “How can I communicate between 2 Fragments in the same Activity?”. I often use 1 of 2 ways that I will detail in this article, that is using Callback and ViewModel.

I have a simple problem as follows: There is an Activity containing 2 Fragmen A and B simultaneously, Fragment A to send data including 1 EditText and 1 Button, Fragment B has 1 TextView, how to click on Button A will display the content in EditText on side B. Use the two methods above to solve this problem.

1. Use Callback

This is a fairly common and familiar way, we will use a callback to transfer data from A to B. Fragment A will have the callback object, when clicking the Send button will call the sendText () method in Callback. We will implement that callback in the activity containing both fragments. To make it easier to imagine, you refer to the following code:

Xml files:

activity_main

fragment_send

fragment_receive

SendFagment

ReceivedFragment

SendTextListenner

MainActivity

The result will be as follows, when entering the text Edittext “This is a message” and click the Send button, will display on the TextView of Fragment B

2. Use the ViewModel

I introduced a little bit about ViewModel. The ViewModel is a class designed to store and manage data in a separate lifecycle, allowing data to be preserved even when the screen is rotated. In the way above, when you rotate the screen leading to Configuration change, your Activity will be reset, resulting in data loss, the TextView content in Fragment B will also be reset to empty. As for using ViewModel, because the data is stored in a separate lifecycle and does not depend on the lifecycle of Activity or Fragment (in the case of screen rotation), the data remains the same, so when you rotate the screen then the data will stay the same.

That said, the next way is to communicate between 2 Fragments via ViewModel. First I will create a class that inherits ViewModel, has a property of type MutableLiveData (you can learn more about LiveData, this article is long, so I will not introduce anymore).

SendTextViewModel

Fragment B will register to listen for changes to the value of the “text” attribute in ViewModel so that when changing the value of the “text” attribute in Fragment A, Fragment B will know the change of that attribute and update it. Updated interface. You can refer to the code below to make it easier to understand.

SendFragment

ReceivedFragment

And of course the result is the same as the way 1 but this method is quite concise and additional bonus case of preserving data when rotating the screen.

3. Summary

I have presented 2 ways I usually use to solve the question raised at the beginning of the article. You use other ways, the comment below for us to learn and apply offline.

Link github here .

Chia sẻ bài viết ngay

Nguồn bài viết : Viblo