How to Pass Data Between Fragments in Android using Kotlin
- August 13, 2019
- John Codeos
Passing data from a Fragment to another Fragment it’s not the same as passing data from one Activity to another. You need first to pass the data to Activity and then to the second Fragment.
If you have created your fragments and you just want to know how to pass data from one Fragment to another, skip the following step.
In this example, we have a fragment that contains an EditText, where we type a text and a Button that sends the text to the 2nd fragment and shows it in a TextView.
First, let’s go and create the layout of the fragment with the EditText and the Button (fragment_1.xml)
Next, let’s do the same for the fragment with the TextView (fragment_2.xml)
Last thing in layouts, let’s go and add an id with a name ‘content_id’ for our parent layout in the activity_main.xml file like the image below:
Now, let’s create the Kotlin class for our first fragment (Fragment1.kt) and second fragment (Fragment2.kt) like that:
Passing Data Between Fragments
When we want to pass data between fragments, we are doing it with the help of the Activity which contains these fragments.
In our example, the Activity is the MainActivity.kt.
So we are going to use the MainActivity to pass the data to the second fragment by using an interface.
In our example we call it Communicator:
Inside the interface there’s a method passDataCom where we will pass the input text from the EditText from our first fragment.
Now, let’s add this Communicator at the top of our MainActivity like that:
After you added it, Android Studio will want to implement the methods.
To do that, press Alt+Enter(Windows) or Command+Enter(MacOS), then Enter and OK on the new window.
Next, let’s go to Fragment1.kt file and initialize our Communicator and call the method, with the text from the EditText as a parameter, like that:
Now it’s time to go back to our MainActivity and pass the value from Fragment1 to the Fragment2.
To do that, we are taking the value and we’re adding it to a Bundle.
Then we pass the bundle data as arguments to the Fragment2
And at the end we display the new fragment by replacing the Fragment1 with the Fragment2 in the MainActivity like that:
In the code above, we gave a key name “input_txt” for our text. This will help us to retrieve the value from our 2nd fragment.
After we have sent the value from the 1st fragment, it’s time to retrieve it from our 2nd fragment and display it on the screen.
Go to our Fragment2 and paste the following code:
Here we’re getting the value with the key name, we put earlier, and we display it on a TextView.
You can find the final project here
If you have any questions feel free to DM me on Twitter @johncodeos or leave a comment below!