![]() |
VOOZH | about |
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.
Using Android Studio create an empty Activity Android Studio project refer to Android | How to Create/Start a New Project in Android Studio?.
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
}
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:
Output UI:
👁 ImageCreate 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:
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:
Fragment 2:
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: