View Binding with Fragments in Android Jetpack
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.
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.
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:
- Fragment 2:
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:
- Fragment 2:
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.