Basic Communication between two fragments (Pass data)

Android Fragment represents a behavior or a portion of user interface in an Activity (or in FragmentActivity). You can use multiple fragments in a single activity to build a multi-pane UI and can reuse a fragment in multiple activities.

Basic Communication between two fragments example

To Use fragments in android you have to build reusable and self-contained modular component. In the process, some time Activity has to multiple Fragments and one fragment can depend on other action or data. So here we are solving and sharing basic Communication between two fragments example.

Consider my 2 fragments Sender and Receiver, and Suppose you need to pass data from Sender to Receiver.

Then create an interface in the Sender, and pass the data to the Main Activity. Then From main activity to pass data fragment Receiver.

 

Let’s start building basic: How to pass data between fragments

Step 1. Create an android project in the android studio (Android First Program in Android Studio)
Step 2. Create 2 fragments in activity_main.xml

Step 3. Create a layout file for sender fragment with a button to send a message

Before copy paste code add color code in res/values/colors.xml otherwise an error will spoil your mood.

Then sender layout file

Step 4. Create Sender fragments from the interface

Interface for communication public interface SenderFragmentListener {... } , with a method void messageFromSenderFragment(String msg);

Step 6. Create a layout file for receiver  fragment with TextView to show

Step 7. Create a fragment for a receiver

with receiving message method public void youGotMsg(String msg) {...} , this method will be called by Activity. In the method, you can do the operation. here we are showing a message in TextView tv_msg.setText(msg);

Step 8. Final step add following code in MainActivity.java

Implements interface implements SenderFragment.SenderFragmentListener in activity and override Method @Override public void messageFromSenderFragment(String msg) {}, then send a message to another fragment.

Step 9. Now Run the application, in an emulator or On your Android device

Output Screenshot: Before

Basic Communication between fragments pass data

 

After click button “SEND HELLO”

Basic Communication between fragments

 

Download Link and Source code in Github

https://github.com/EyeHunts/BasicCommunicationbetweenfragments/

 

Note : This example (Project) is developed in Android Studio 3.0.1 ,tested on Android 7.1.1 ( Android Nougat), compile SDK version API 26: Android 8.0 (Oreo)

MinSdkVersion=”15″

TargetSdkVersion=”26″

Coding in JAVA

 

Bonus: For share data between fragment using ViewModel check this tutorial: Share data between fragments used ViewModel example


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.