Skip to content

Instantly share code, notes, and snippets.

@n8ebel
Created November 22, 2017 07:10
Show Gist options
  • Save n8ebel/803804c29b073f94ae53187c55d8a538 to your computer and use it in GitHub Desktop.
Save n8ebel/803804c29b073f94ae53187c55d8a538 to your computer and use it in GitHub Desktop.
A custom Kotlin delegate for initializing ViewDataBinding objects for Android databinding
/**
* Provides a [ViewDataBinding] object of the declared type by
* calling [DataBindingUtil.setContentView] with the property owning [Activity] and the specified
* layout resource id
*/
class ActivityBindingProvider<out T : ViewDataBinding>(
@LayoutRes private val layoutRes: Int) : ReadOnlyProperty<Activity, T> {
private var binding : T? = null
override operator fun getValue(thisRef: Activity, property: KProperty<*>): T {
return binding ?: createBinding(thisRef).also{ binding = it }
}
private fun createBinding(activity: Activity):T {
return DataBindingUtil.setContentView(activity, layoutRes)
}
}
class FooActivity : Activity {
val binding:ActivityFooBinding by ActivityBindingProvider(R.layout.activity_foo)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment