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:
View Binding with Fragments in Android Jetpack
Next article icon

View Binding with Fragments in Android Jetpack

Last Updated : 07 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In the Previous article View Binding in Android Jetpack, it's been discussed why acquiring the ViewBinding feature in the Android project provides a lot of benefits. But when it comes to ViewBinding with fragments the scenario changes. Because the lifecycle of the Fragment is different and that of activity is different Here also things go the same as discussed in the above article the naming conventions of the fragment layout are changed to pascal case and properties of the fragment layout to camel case. For Example, fragment1.xml -> Fragment1Binding and edit_text(id) which is under the fragment's layout changes to eEditText(camel case) So in this article ViewBinding is discussed using Fragments. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Kotlin language. 

Step by Step Implementation

Step 1: Create a new empty activity project

Using Android Studio create an empty Activity Android Studio project refer to Android | How to Create/Start a New Project in Android Studio?.

Step 2: Enable the ViewBinding feature

Enable the ViewBinding feature by invoking the following code snippet inside the app-level build.gradle file, and click on the "Sync Now" buttons which appear on the top-right corner.

buildFeatures {

       viewBinding = true

}


Step 3: Working with the activity_main.xml file

The main layout of the activity contains two buttons, to toggle fragment 1 and fragment 2, and one Framelayout to hold the fragments inside the CardView. And one Submit button to check when pressed whose fragment's data is submitted. To implement the same invoke the following code inside the activity_main.xml file.

activity_main.xml:

XML
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout      xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:app="http://schemas.android.com/apk/res-auto"     xmlns:tools="http://schemas.android.com/tools"     android:layout_width="match_parent"     android:layout_height="match_parent"     tools:context=".MainActivity"     tools:ignore="HardcodedText">      <Button         android:id="@+id/fragment_1B"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_marginTop="16dp"         android:text="FRAGMENT 1"         app:layout_constraintEnd_toStartOf="@+id/fragment_2B"         app:layout_constraintHorizontal_bias="0.5"         app:layout_constraintStart_toStartOf="parent"         app:layout_constraintTop_toTopOf="parent" />      <Button         android:id="@+id/fragment_2B"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_marginTop="16dp"         android:text="FRAGMENT 2"         app:layout_constraintEnd_toEndOf="parent"         app:layout_constraintHorizontal_bias="0.5"         app:layout_constraintStart_toEndOf="@+id/fragment_1B"         app:layout_constraintTop_toTopOf="parent" />      <androidx.cardview.widget.CardView         android:id="@+id/card_view"         android:layout_width="match_parent"         android:layout_height="256dp"         android:layout_marginStart="16dp"         android:layout_marginTop="16dp"         android:layout_marginEnd="16dp"         app:layout_constraintEnd_toEndOf="parent"         app:layout_constraintStart_toStartOf="parent"         app:layout_constraintTop_toBottomOf="@+id/fragment_1B">          <FrameLayout             android:id="@+id/fragment_holder"             android:layout_width="match_parent"             android:layout_height="wrap_content"             android:layout_marginStart="8dp"             android:layout_marginEnd="8dp" />      </androidx.cardview.widget.CardView>      <Button         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:layout_marginStart="16dp"         android:layout_marginTop="16dp"         android:layout_marginEnd="16dp"         android:text="SUBMIT"         app:layout_constraintEnd_toEndOf="parent"         app:layout_constraintStart_toStartOf="parent"         app:layout_constraintTop_toBottomOf="@+id/card_view" />  </androidx.constraintlayout.widget.ConstraintLayout> 


Output UI:


Step 4: Creating two fragments

Create two fragments, which include text view to represent fragment number edit text and a button. To implement the UI of each fragment you may refer to the following codes.

Fragment 1:

XML
<?xml version="1.0" encoding="utf-8"?> <!--fragment 1--> <LinearLayout      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"     android:orientation="vertical"     tools:context=".ExampleFragment1"     tools:ignore="HardcodedText">      <TextView         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_marginStart="16dp"         android:layout_marginTop="16dp"         android:text="Fragment 1"         android:textSize="18sp" />      <EditText         android:id="@+id/edit_text1"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:layout_marginStart="16dp"         android:layout_marginTop="16dp"         android:layout_marginEnd="16dp"         android:hint="Enter Something" />      <Button         android:id="@+id/done_button1"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_gravity="end"         android:layout_marginTop="8dp"         android:layout_marginEnd="16dp"         android:text="DONE" />  </LinearLayout> 


Fragment 2:

XML
<?xml version="1.0" encoding="utf-8"?> <!--fragment 2--> <LinearLayout      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"     android:orientation="vertical"     tools:context=".ExampleFragment2"     tools:ignore="HardcodedText">      <TextView         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_marginStart="16dp"         android:layout_marginTop="16dp"         android:text="Fragment 2"         android:textSize="18sp" />      <EditText         android:id="@+id/edit_text2"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:layout_marginStart="16dp"         android:layout_marginTop="16dp"         android:layout_marginEnd="16dp"         android:hint="Enter Something" />      <Button         android:id="@+id/done_button2"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_gravity="end"         android:layout_marginTop="8dp"         android:layout_marginEnd="16dp"         android:text="DONE" />  </LinearLayout> 


Step 5: Working with the Fragments.kt files

Firstly the binding variable which is nullable is assigned to null initially, and also when the view of the fragment gets destroyed, again it has to be set null (which in this case _binding). And to avoid the null check of the nullable binding object, by using the backing property of the kotlin we make another copy of the binding variable (which in this case binding).

However, if the fragment wants to access the views from the host activity, can be done using the findViewById() method.

Fragment 1:

Kotlin
import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.Toast import androidx.fragment.app.Fragment  // Enter your package name here import com.adityamshidlyali.gfgarticle.databinding.Fragment1Binding  class ExampleFragment1 : Fragment() {      // assign the _binding variable initially to null and     // also when the view is destroyed again it has to be set to null     private var _binding: Fragment1Binding? = null      // with the backing property of the kotlin we extract     // the non null value of the _binding     private val binding get() = _binding!!      override fun onCreateView(             inflater: LayoutInflater, container: ViewGroup?,             savedInstanceState: Bundle?     ): View {          // inflate the layout and bind to the _binding         _binding = Fragment1Binding.inflate(inflater, container, false)          // retrieve the entered data by the user         binding.doneButton1.setOnClickListener {             val str: String = binding.editText1.text.toString()             if (str.isNotEmpty()) {                 Toast.makeText(activity, str, Toast.LENGTH_SHORT).show()             } else {                 Toast.makeText(activity, "Please Enter Data", Toast.LENGTH_SHORT).show()             }         }          // handle the button from the host activity using findViewById method         val submitButton: Button = activity!!.findViewById(R.id.submit_button)         submitButton.setOnClickListener {             Toast.makeText(activity, "Host Activity Element Clicked from Fragment 1", Toast.LENGTH_SHORT).show()         }          // Inflate the layout for this fragment         return binding.root     }      override fun onDestroyView() {         super.onDestroyView()         _binding = null     } } 


Fragment 2:

Kotlin
import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.Toast import androidx.fragment.app.Fragment  // Enter your package name here import com.adityamshidlyali.gfgarticle.databinding.Fragment2Binding  class ExampleFragment2 : Fragment() {      // assign the _binding variable initially to null and     // also when the view is destroyed again it has to be      // set to null     private var _binding: Fragment2Binding? = null      // with the backing property of the kotlin     // we extract     // the non null value of the _binding     private val binding get() = _binding!!      override fun onCreateView(             inflater: LayoutInflater, container: ViewGroup?,             savedInstanceState: Bundle?     ): View {          // inflate the layout and bind to the _binding         _binding = Fragment2Binding.inflate(inflater, container, false)          // retrieve the entered data by the user         binding.doneButton2.setOnClickListener {             val str: String = binding.editText2.text.toString()             if (str.isNotEmpty()) {                 Toast.makeText(activity, str, Toast.LENGTH_SHORT).show()             } else {                 Toast.makeText(activity, "Please Enter Data", Toast.LENGTH_SHORT).show()             }         }          // handle the button from the host activity using findViewById method         val submitButton: Button = activity!!.findViewById(R.id.submit_button)         submitButton.setOnClickListener {             Toast.makeText(activity, "Host Activity Element Clicked from Fragment 2", Toast.LENGTH_SHORT).show()         }          // Inflate the layout for this fragment         return binding.root     }      override fun onDestroyView() {         super.onDestroyView()         _binding = null     } } 


Step 6: Working with the MainActivity.kt file

In the MainActivity.kt file only the transaction functionality of the fragments is implemented. Refer to the following code and its output for better understanding.

MainActivity.kt:

Kotlin
import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.fragment.app.Fragment import com.adityamshidlyali.gfgarticle.databinding.ActivityMainBinding  class MainActivity : AppCompatActivity() {      // create binding instance for the activity_main.xml     private lateinit var binding: ActivityMainBinding      override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState)         binding = ActivityMainBinding.inflate(layoutInflater)         setContentView(binding.root)          // when app is initially opened the Fragment 1 should be visible         supportFragmentManager.beginTransaction().apply {             replace(binding.fragmentHolder.id, ExampleFragment1())             addToBackStack(null)             commit()         }          // handle the fragment 2 button to toggle the fragment 2         binding.fragment1B.setOnClickListener {             changeFragment(ExampleFragment1())         }          // handle the fragment 2 button to toggle the fragment 2         binding.fragment2B.setOnClickListener {             changeFragment(ExampleFragment1())         }     }      // function to change the fragment which is     // used to reduce the lines of code     private fun changeFragment(fragmentToChange: Fragment): Unit {         supportFragmentManager.beginTransaction().apply {             replace(binding.fragmentHolder.id, fragmentToChange)             addToBackStack(null)             commit()         }     } } 

Output:


Next Article
View Binding with Fragments in Android Jetpack

A

adityamshidlyali
Improve
Article Tags :
  • Technical Scripter
  • Android
  • Technical Scripter 2020
  • Android-Jetpack

Similar Reads

    View Binding in Android Jetpack
    View Binding is one of the best features in Android that allows views to bind seamlessly with an ongoing activity. It replaces the traditional findViewById()method, significantly reducing boilerplate code by automatically generating instances of views for the current layout. One of its most importan
    3 min read
    Building UI Using Jetpack Compose in Android
    Jetpack Compose is a modern UI toolkit that is designed to simplify UI development in Android. It consists of a reactive programming model with conciseness and ease of Kotlin programming language. It is fully declarative so that you can describe your UI by calling some series of functions that will
    7 min read
    Jetpack LiveData in Android with Example
    Android Jetpack is a suite of libraries to help developers follow best practices, reduce boilerplate code, and write code that works consistently across Android versions and devices so that developers can focus on the code they care about. Here, we are going to implement Jetpack Live Data in Android
    4 min read
    ViewPager Using Fragments in Android with Example
    ViewPager is a layout manager that allows the user to flip left and right through pages of data. It is a depreciated concept we are using ViewPager2 now. It is mostly found in apps like Youtube, Snapchat where the user shifts right-left or top-bottom to switch to a screen. Instead of using activitie
    6 min read
    Data Binding in Android: Activities, Views, and Fragments
    Data binding in Android is one of the most effective features for Android developers to bind the UI controls present in the layout with the data resources in the code. This makes the code less complicated and readable thus enhancing the overall maintainability of the application. In this article, I
    4 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