View Binding with Fragments in Android Jetpack
Last Updated :
07 Apr, 2025
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:
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
Data Binding with ViewModel in Android
DataBinding is one of the most important concepts to really improve the performance of your Android Application It plays a vital role in the maintenance of the many Android Architectures. In this article, we will learn about DataBinding in ViewModel In Android. Benefits of integrating Data binding i
5 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
Scratch Card View in Android with Example
Scratch Card View is one of the most seen UI components in Android apps. This type of UI component is generally seen in payment apps such as Google Pay and many other payment apps. Now if you are an Android developer then you should get amazed at How we can create this type of UI component in our An
3 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
How to Implement View Binding Inside Dialog in Android?
In android, View binding is a feature that allows you to more easily write code that interacts with views. Once view binding is enabled in a module, it generates a binding class for each XML layout file present in that module. An instance of a binding class contains direct references to all views th
4 min read
Android ListView in Java with Example
A ListView in Android is a type of AdapterView that displays a vertically scrollable list of items, with each item positioned one below the other. Using an adapter, items are inserted into the list from an array or database efficiently. For displaying the items in the list method setAdaptor() is use
3 min read
Jetpack Navigation Component in Android
The Navigation Architecture Component simplifies navigation implementation while also assisting you in visualizing your app's navigation flow. The library offers a variety of advantages, including:Handling of fragment transactions automaticallyBy default, up and back actions are handled correctly.De
4 min read