The Wayback Machine - https://web.archive.org/web/20241115021513/https://www.geeksforgeeks.org/view-binding-with-fragments-in-android-jetpack/
Open In App

View Binding with Fragments in Android Jetpack

Last Updated : 25 Feb, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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

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

}

  • Refer to the following image if unable to locate the app-level build.gradle file invokes the above build feature.

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.

XML




<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    tools:ignore="HardcodedText"
    tools:viewBindingIgnore="true">
  
    <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: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: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.
  • Invoke the following code inside each of the fragment’s .kt files. Comments are added for better understanding.
  • 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.

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

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 will be explaining what data binding is; how to im
4 min read
View Binding in Android Jetpack
View Binding is one of the best features which provides the views to bind with the activity which is ongoing. Replacing the findViewById() method, hence reducing the boilerplate code, generated the instances of the views of the current layout. And most important feature about the View Binding is it's always null safe. In this article detailed it's
4 min read
How to Use View Binding in RecyclerView Adapter Class in Android?
View Binding is a part of Android Jetpack which provides the views to bind with the classes by replacing the findViewById() method in a null safe way. In this article, we will see its implementations in the Adapter class of RecyclerView. Note that we are going to implement this project using the Kotlin language. Step by Step Implementation Step 1:
5 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 that have an ID in the corresponding layout. What we
4 min read
How to Implement findViewById in Fragments in Android?
Fragments represent a part of the app's UI which is reusable. Fragments are having its own layout, and lifecycle but must be hosted inside an activity to be visible. The activity becomes easier to modify if it consists of many fragments. A fragment can have multiple instances inside an activity. findViewById finds the view by the given ID. Step By
3 min read
How to Implement onBackPressed() in Fragments in Android?
In Android, the Fragment is the part of the Activity that represents a portion of the User Interface(UI) on the screen. It is the modular section of the android activity that is very helpful in creating UI designs that are flexible in nature and auto-adjustable based on the device screen size. onBackPressed() is a method that is to be implemented i
3 min read
Introduction to Fragments | Android
Fragment is a piece of an activity that enables a 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 layouts and their logic. You can build single-pan
5 min read
How to Communicate Between Fragments in Android?
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
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 mostly found in apps like Youtube, Snapchat where the user shifts right - left to switch to a screen. Instead of using activities fragments are used. It is also used to guide the user through the app when the user launches the app for the first ti
7 min read
Android Jetpack Compose - Implement Zoomable View
Jetpack Compose is a new UI toolkit from Google used to create native Android UI. It speeds up and simplifies UI development using less code, Kotlin APIs, and powerful tools. Prerequisites:Familiar with Kotlin and OOP Concepts as wellBasic understanding of Jetpack ComposeAndroid Studio Canary Version A sample video is given below to get an idea abo
9 min read
Android Runtime Permissions with Dexter using Android Jetpack Compose
Android applications require the usage of hardware devices within the android applications such as microphones or cameras. For using these devices within any android application. Permissions for using this hardware have to be provided to the application. For giving these permissions to the application runtime permissions are used. Handling permissi
7 min read
Overview of Data Binding in Android Architecture Components
This article describes the idea behind the Data Binding and MVVM design pattern and its components. If you would like to experiment with it hands-on, open an old project with spaghetti code. If you don’t have one, you'll get one from GitHub. Then, attempt to use the MVVM components introduced during this article. In some ways, software development
4 min read
Data Binding with LiveData in Android
Prerequisite: DataBindingLiveData and ViewModel So, Why we are using Data binding with LiveData? Actually, If we want our views to directly communicate with ViewModel (Data source), we can do that simply without using LiveData. But if data changes in ViewModel it won't reflect its View. This is where we can take the help of LiveData, to automatical
2 min read
Synthetic Binding in Android
In android application development, for every view in the XML, we need to get an instance of that view to get access to it for doing any operation on it, like changing any property of a view. This is a very common requirement in any android application development cycle. There are main two ways of android development. Data Binding: Data Binding Lib
3 min read
Data Binding in Android with Example
In Android, the Data Binding Library is a support library that allows you to bind UI components in your layouts to data sources in your app using a declarative format rather than programmatically. What we are going to build in this article?Here is a sample video of what we are going to build in this project. Note that we are going to make this proj
4 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 in ViewModel There are many benefits of using two i
5 min read
Horizontal ListView in Android using Jetpack Compose
Many Android Applications present data in the form of horizontally scrollable lists. This list can be scrolled horizontally. In this article, we will take a look at How to Implement Horizontal ListView in Android Applications using Jetpack Compose. Note: If you are seeking Java code for Jetpack Compose, please note that Jetpack Compose is only avai
6 min read
Material Design Text Input Field using Jetpack Compose in Android
Jetpack Compose is a modern toolkit for building native Android UI. Jetpack Compose simplifies and accelerates UI development on Android with less code, powerful tools, and intuitive Kotlin APIs. Compose is built to support material design principles. Many of its UI elements implement material design out of the box. In this article, we will explain
3 min read
How to Remove TextField Padding in Android using Jetpack Compose?
In Android Jetpack Compose, a TextField is used to take input from the user in the form of text. TextField when in focus or when clicked invokes a soft keyboard. In general, TextField is highly attributed for a better feel and appearance. However, we can use a pre-developed TextField, named BasicTextField, which has no attributes like that of a reg
3 min read
WebView in Android using Jetpack Compose
In Android, a WebView is an extension of View Class that allows us to display webpages. In simpler words, if you want to display a webpage in Activity Layout, then you can implement a WebView to display it. It is very similar to a browser but isn't one. A WebView can rather be referred to as a show or a preview of a browser as it lacks most functio
3 min read
Motion Layout Button in Android Jetpack Compose
Motion Layout is a special version of Constraint layout. With the help of motion layout, we can add animations to the widgets within the layout and change the position of that widget dynamically. In this article, we will take a look at How to implement Motion Layout animation on buttons in Android using Jetpack compose. What we are going to build i
8 min read
Play Audio in Android using Jetpack Compose
In Android, a MediaPlayer is used to play media files like audio and video files in the application. The MediaPlayer Class uses the MediaPlayer API for performing various functions like creating a MediaPlayer, playing, pausing, starting, and stopping the media. In this article, we will show you how you could play an Audio File on Android using Jetp
3 min read
Android Jetpack - WorkManager with Example
WorkManager is an Android Jetpack library that provides a flexible and efficient way to schedule and manage background tasks in your app. It is a powerful and recommended tool for managing background processing in Android applications. With WorkManager, you can schedule asynchronous, deferred, and periodic tasks that need to run even when the app i
5 min read
Curved Text in Android using Jetpack Compose
In Android, there are no inbuilt schemes to implement designed text like the word art, which is available in applications like MS Word. We can always refer to or download such schemes like designed font faces to implement designed text. However, it is also possible to natively build (building from scratch) such designed texts in an Android Project.
3 min read
How to Get Screen Width and Height in Android using Jetpack Compose?
Android applications are being developed for different device orientations to support a huge range of devices. So that users with different device size configurations can use the application. Many applications need to get the height and width of the device screen to create UI. In this article, we will take a look at How to get Screen Width and Heig
5 min read
Extract Data From PDF File using Android Jetpack Compose
PDF files are used in many android applications for displaying data in the form of images, text as well as graphics. Many applications are also required to get the data from this PDF file and display this data within the android application. So for extracting the data from PDF file pdf reader is used which is used to read pdf and get the data from
6 min read
Introduction to Android Jetpack
The Android support libraries are used in almost all android applications to overcome the compatibility issues across different Android OS versions and devices. These libraries also facilitate users to add various kinds of updated widgets in the application. Over time, these libraries are updated according to the latest android versions. The proble
6 min read
Jetpack Compose Navigation and Passing Data in Android
Almost every app uses some kind of navigation, allows users to move from one screen to another. In this article, we will learn to implement Navigation in Jetpack Compose using Compose way. We will build a simple app demonstrating Jetpack compose navigation, It will have three screens(Home, Profile, and Settings). It will navigate to Settings Screen
4 min read
Foundation Components of Android Jetpack
Android Jetpack is a set of software components, libraries, tools, and guidance to help in developing robust Android applications. Launched by Google in 2018, Jetpack comprises existing android support libraries, android architecture components with an addition of the Android KTX library as a single modular entity. Nowadays, nearly 99% of the apps
7 min read
Behaviour Components of Android Jetpack
Android Jetpack is a set of software components, libraries, tools, and guidance to help in developing robust Android applications. Launched by Google in 2018, Jetpack comprises existing android support libraries, android architecture components with an addition of the Android KTX library as a single modular entity. Nowadays, nearly 99% of the apps
10 min read
three90RightbarBannerImg