Skip to content

Instantly share code, notes, and snippets.

@n8ebel
Last active September 14, 2017 01:26
Show Gist options
  • Save n8ebel/a2c209a4aa294b3a76575ef5235aeee1 to your computer and use it in GitHub Desktop.
Save n8ebel/a2c209a4aa294b3a76575ef5235aeee1 to your computer and use it in GitHub Desktop.
ViewDataBinding extension to provide a more readable api for setting data into a binding object
  • Define an extension function on ViewDataBinding to provide a readable api for setting data into a binding object
  • Usage is equivalent to use .apply{} but is more explicit about the desried usage
inline fun <T : ViewDataBinding> T.bindData(block: T.() -> Unit): T { block(); return this }
// Use the extension function to set the data into the binding object in a very readable way
//
DataBindingUtil.setContentView<ActivityMainBinding>(this, R.layout.activity_main).bindData {
message = "hello"
number = 5
}
// Essentially equivalent to this, but possibly more readable
//
DataBindingUtil.setContentView<ActivityMainBinding>(this, R.layout.activity_main).apply {
message = "hello"
number = 5
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment