Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java for Android
  • Android Studio
  • Android Kotlin
  • Kotlin
  • Flutter
  • Dart
  • Android Project
  • Android Interview
Open In App
Next Article:
How to Communicate Between Fragments in Android?
Next article icon

How to Communicate Between Fragments in Android?

Last Updated : 08 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Nowadays most apps have so many features so for that they use multiple fragments in a single app and communication is one of the important parts of apps for sharing data from one fragment to another because two fragments can't communicate directly. A Fragment represents a portion of any user interface. There can be a number of fragments within one activity. They have their own life cycle.

Approach

There are multiple ways in which we can communicate within apps:

  • We can communicate within fragments using the ViewModel.
  • We can also communicate between fragments using an Interface.

In this article, we are going to explain how to communicate between fragments using the Interface using Kotlin.

Step-by-Step Implementation

Step 1: Create a New Project in your android studio 

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.

Step 2: Create two blank fragments 

Navigate to your Project file where MainActivity.kt exists. Right-click on that folder and click on the new package and name it fragments. Now inside this newly created folder create two blank fragments and name them Fragment1 & Fragment2.

Step 3: Working with XML files

Navigate to the app > res > layout > fragment1.xml and add the below code to that file. Below is the code for the fragment1.xml file. 

XML
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout      xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:tools="http://schemas.android.com/tools"     android:layout_width="match_parent"     android:layout_height="match_parent"     tools:context=".fragments.Fragment1">      <!-- Text View for showing Fragment1 text -->     <TextView         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:text="Fragment 1"         android:textSize="40sp"         android:layout_centerHorizontal="true"         android:gravity="center"         android:layout_marginTop="20dp"         android:textColor="@color/black"/>        <!-- Edit Text for taking user input -->     <EditText         android:id="@+id/messageInput"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:text="Enter text to Pass"         android:layout_marginTop="200dp"         android:gravity="center"         android:layout_marginLeft="30dp"         android:layout_marginRight="30dp"         android:textSize="30sp"/>       <!-- Button for submit user response -->     <Button         android:id="@+id/sendBtn"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:layout_below="@+id/etText"         android:text="Submit"         android:backgroundTint="#0F9D58"         android:textSize="20sp"         android:textAllCaps="false"         android:layout_marginLeft="30dp"         android:layout_marginRight="30dp"         android:layout_marginTop="20dp" />  </RelativeLayout> 


Navigate to the app > res > layout > fragment2.xml and add the below code to that file. Below is the code for the fragment2.xml file. 

XML
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout      xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:tools="http://schemas.android.com/tools"     android:layout_width="match_parent"     android:layout_height="match_parent"     tools:context=".fragments.Fragment2">      <!-- Text View for showing Fragment2 text -->     <TextView         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:text="Fragment 2"         android:textSize="40sp"         android:layout_centerHorizontal="true"         android:gravity="center"         android:layout_marginTop="20dp"         android:textColor="@color/black"/>      <!-- Frame Layout which will replaced by data from Fragment1 -->     <FrameLayout         android:id="@+id/frameLayout"         android:layout_width="match_parent"         android:layout_height="wrap_content">          <TextView             android:id="@+id/displayMessage"             android:layout_width="match_parent"             android:layout_height="wrap_content"             android:text="Text"             android:textSize="30sp"             android:layout_centerHorizontal="true"             android:gravity="center"             android:layout_marginTop="300dp"             android:textColor="@color/black"/>      </FrameLayout>  </RelativeLayout> 


Step 4: Create Interface

Again navigate to your Project folder where MainActivity.kt exists and right-click on that folder -> new -> Kotlin class/file -> Interface them name it as Communicator.

Kotlin
package com.mrtechy.gfg  interface Communicator {     fun passData(editTextInput:String) } 


Step 5: Working With the MainActivity.kt 

Kotlin
package com.mrtechy.gfg  import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import com.mrtechy.gfg.fragments.Fragment1 import com.mrtechy.gfg.fragments.Fragment2  class MainActivity : AppCompatActivity(), Communicator {     override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState)         setContentView(R.layout.activity_main)          // created instance of Fragment1         val fragment1 = Fragment1()          // Frame manager called to replace Fragment2 frame layout with Fragment1 data         supportFragmentManager.beginTransaction().replace(R.id.frameLayout,fragment1).commit()     }      // Override function which we     // have created in our interface     override fun passData(editTextInput: String) {         val bundle = Bundle()         bundle.putString("message", editTextInput)          val transaction = this.supportFragmentManager.beginTransaction()                  // Created instance of fragment2         val fragment2 = Fragment2()          fragment2.arguments = bundle         transaction.replace(R.id.frameLayout,fragment2)         transaction.commit()     } } 


Step 6: Working With Fragment1 & Fragment file

Below is the code for the Fragment1.kt and Fragment2.kt files respectively. 

Kotlin
package com.mrtechy.gfg.fragments  import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.EditText import com.mrtechy.gfg.Communicator import com.mrtechy.gfg.R  class Fragment1 : Fragment() {      private lateinit var communicator: Communicator      override fun onCreateView(         inflater: LayoutInflater, container: ViewGroup?,         savedInstanceState: Bundle?     ): View? {                // Inflate the layout for this fragment         val view = inflater.inflate(R.layout.fragment_1, container, false)          communicator = activity as Communicator                // there are button and edittext id which we have saved         val button:Button = view.findViewById(R.id.sendBtn)         val textMessage:EditText = view.findViewById(R.id.messageInput)          // pass data to our interface while          // button clicked using setOnClickListener         button.setOnClickListener {             communicator.passData(textMessage.text.toString())         }          return view      }  } 
Kotlin
package com.mrtechy.gfg.fragments  import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import com.mrtechy.gfg.R  class Fragment2 : Fragment() {      // initialised a empty string variable     var displayMessage:String? =""      override fun onCreateView(         inflater: LayoutInflater, container: ViewGroup?,         savedInstanceState: Bundle?     ): View? {                // Inflate the layout for this fragment         val view = inflater.inflate(R.layout.fragment_2, container, false)         val displayM:TextView = view.findViewById(R.id.displayMessage)          // get text from interface and send          // to textView present in Fragment2         displayMessage = arguments?.getString("message")         displayM.text = displayMessage         return view     }  } 

Output:



Next Article
How to Communicate Between Fragments in Android?

I

iamabhijha
Improve
Article Tags :
  • Kotlin
  • Android

Similar Reads

    How to Create a New Fragment in Android Studio?
    Android Studio is the official integrated development environment for Google's Android operating system, built on JetBrains' IntelliJ IDEA software and designed specifically for Android development. You can Develop Android App using this. Here, We are going to learn how to create a new Fragment in A
    2 min read
    Dynamic Fragment in Android
    Dynamic Fragment is a type of fragment that is defined in an XML layout file and called using FragmentManager class. The FragmentManager class is responsible for managing fragments. It is a part of the Activity and its lifecycle depends on the lifecycle of its container activity. Dynamic Fragments a
    4 min read
    How to Save Fragment States with BottomNavigationView in Android?
    In Android applications, Activities and Fragments are from the foundation of the UI layer. It is now standard practice to load the UI with multiple fragments. For example, Instagram, Twitter, and a slew of other well-known apps. Imagine browsing some tweets in the Twitter app's HomeFragment, navigat
    4 min read
    Fragment to Fragment Communication in Android using Shared ViewModel
    If there are two or more fragments in an activity, they need to communicate and share the data between them. The traditional way of sharing the data between the two fragments is implementing the callback using an interface that is cumbersome and may throw exceptions. But the modern way of doing that
    6 min read
    How to Get Current Location Inside Android Fragment?
    A Fragment is a piece of an activity that enables more modular activity design. A fragment encapsulates functionality so that it is easier to reuse within activities and layouts. Android devices exist in a variety of screen sizes and densities. Fragments simplify the reuse of components in different
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences