Advanced Data Binding in Android: Binding Adapters
Dec 6 2021
, Kotlin 1.5, Android 4.4, Android Studio 2020.3.1Kotlin 1.5, Android 4.4, Android Studio 2020.3.1
In this advanced data binding tutorial, you’ll learn how you can interact directly with the components in your layouts, assign a value and handle events dispatched by the views using binding adapters.
By Rodrigo Guerrero.
You’re adding the annotation @BindingAdapter, which will respond to values set to crewFilter. Depending on CrewAgency, the adapter returns the ID that will select the correct radio button. To prevent infinite cycles, you need to add an if condition to check the radio button only if the selected ID has changed.
The next step is to return a CrewAgency depending on the selected radio button.
Creating an InverseBindingAdapter
To achieve this, you need to create an inverse binding adapter. In RadioGroupBindingAdapter.kt, add the following code:
Here, you add @InverseBindingAdapter to a method and set the attribute name to which this inverse binding adapter will respond. It should always be the same attribute name as the one used in the normal binding adapter. In this case, the attribute name is crewFilter.
Finally, the binding adapters need a way to know when the attributes change.
Binding Listener Methods
To give the binding adapters a way to listen for changes in their attributes, add the following code to RadioGroupBindingAdapters.kt:
This is a binding adapter for the attribute app:crewFilterAttrChanged. The name of this attribute is the name you give to your attribute plus AttrChanged. This adapter receives InverseBindingListener. This listener has one method: onChange(). In this case, you’ll call onChange() whenever the checked state of the radio button changes.
Finally, it’s time to use two-way data binding. Open fragment_crew.xml and modify RadioGroup as follows:
Here, you assign the instance of viewModel to the binding, so the layout has access to it.
Note: You might see an error in binding?.viewModel. Remember to build the project after adding <data> to the layout so that Android Studio creates the necessary files for you.
Build and run. Open the Crew tab. Select any radio button to filter the crew by agency. You’ll see something similar to the image below:
Great job! You’ve implemented two-way data binding.
Where to Go From Here?
Download the final project by using the Download Materials button at the top or bottom of the tutorial.
I hope you enjoyed this tutorial on data binding. If you have any questions or comments, please join the forum discussion below.
All videos. All books.
One low price.
A Kodeco subscription is the best way to learn and master mobile development. Learn iOS, Swift, Android, Kotlin, Flutter and Dart development and unlock our massive catalog of 50+ books and 4,000+ videos.