Android Passing Data Between Fragments With Examples

In this tutorial, we’ll be developing an application that contains TabLayout, ViewPager and Fragments. We’ll implement a functionality that passes data from one Fragment to the other fragment.

Android Passing Data between Fragments

Intents are only usable for sending data on an Activity level. To pass data between fragments we need to create our own interfaces. The flow to send a String data from one Fragment to another is shown below.

android-passing-data-between-fragments-flow

Let’s get started with the implementation of the above flow.

Android Passing Data between Fragments Project Structure

android-passing-data-between-fragments-project

The xml layout for the MainActivity.java class is given below.

The styles for the TabLayout and ToolBar are defined in the styles.xml file as shown below.

The ViewPagerAdapter.java is where the Fragments are initialised. The code is given below.

FragmentOne would be sending the data entered in EditText to FragmentTwo.

The xml layout for fragment_one.xml is given below.

The xml layout for fragment_two.xml is given below.

The code for FragmentOne.java class is given below.

The Custom Interface namely SendMessage is initialised in the onAttach method above. This interface would be implemented in the MainActivity.java that we’ll be seeing shortly.

The code for FragmentTwo.java class is given below.

The displayReceivedData() would be called on the instance of FragmentTwo.java from inside the Custom Interface’s method inside the MainActivity.java as shown below.

The sendData() method in the above code gets triggered as soon as the Button in FragmentOne is pressed. We fetch the FragmentTwo that was already initialised in ViewPagerAdapter using the method findFragmentByTag.

The output of the above application in action is given below.
android passing data between fragments, android sharing object between fragments example

This brings an end to this tutorial. You can download the final Android PassingDataBetweenFragments Project from the link below.

Reference: Fragment Communication

By admin

Leave a Reply

%d bloggers like this: