Data Binding and
Kotlin
ETON OTIENO
@eton_otieno
@CodeZilla7
Slide 2
Slide 2 text
Project Set Up
Slide 3
Slide 3 text
Converting existing layouts to data
binding layouts
Slide 4
Slide 4 text
Converting existing layouts to data
binding layouts
Slide 5
Slide 5 text
The Expression Language
Data Binding provides expressions which can be used in your layouts.
Use them minimally because placing logic in your layouts makes testing
impossible.
There are some useful ones like the null coalescing operator and the
ternary operand. The null coalescing operator choses the left operand
if it isn’t null or the right if the left is null.
Slide 6
Slide 6 text
The Expression Language
Data binding also supports using imports in your layouts
Slide 7
Slide 7 text
Binding your data to views
Let’s create a model with the data we require.
By using a data class you get methods like toString(), equals() ,
hashCode() and copy() automatically, you don’t have to override
them.
Slide 8
Slide 8 text
Binding your data to views
Slide 9
Slide 9 text
Binding your data to views
Slide 10
Slide 10 text
Binding your data to views
As I had earlier said, you shouldn’t put complex logic in your XML,
instead use ViewModels. It’s testable and you’ll get to write more Kotlin
code.
You can get a reference to the ViewModel using the variable tag in
your layout.
Slide 11
Slide 11 text
Binding your data to views
Slide 12
Slide 12 text
Cleaning up with Kotlin
Slide 13
Slide 13 text
Cleaning up with Kotlin
Slide 14
Slide 14 text
Data Binding Adapters
Data binding adapters are responsible for calling the appropriate framework
methods to set the values of your layout views.
You can also define custom attributes in your XML layouts with custom binding
adapters.
Slide 15
Slide 15 text
Data Binding Adapters
Hold on for a second, what type of attribute is errorImage?
This is one of the many parts of data binding that really shines.
With custom binding adapters, you don’t have to write custom attributes
in your custom view; just use a binding adapter.
Slide 16
Slide 16 text
Data Binding Adapters
Let’s say for example you have a setImageShadowBackground(Int) in
your custom view, you can use the attribute imageShadowBackground
attribute in your layout!
Slide 17
Slide 17 text
Data Binding Adapters
Slide 18
Slide 18 text
Data Binding Adapters
Data binding will call the appropriate function in your custom view.
This also works with the android framework classes that have setter
methods but no layout attributes. The DrawerLayout is a good
example.
Slide 19
Slide 19 text
Data Binding Adapters
So, how can you use the attributes I showed you earlier on? Let’s
write some Kotlin code!
Slide 20
Slide 20 text
Data Binding Adapters
If you prefer using an object instead of declaring the binding adapter as a top
level function, remember to annotate the function as @JvmStatic