Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Data Binding and Kotlin

Data Binding and Kotlin

In this session you'll dive deeper into the Data Binding library and learn some Kotlin tips and tricks.

Eton Otieno

October 04, 2018
Tweet

Other Decks in Programming

Transcript

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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.
  6. 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!
  7. 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.
  8. Data Binding Adapters  So, how can you use the

    attributes I showed you earlier on? Let’s write some Kotlin code!
  9. 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
  10. Thank You! I had a great time being your data

    binding sensei for this session!