Created
November 22, 2017 07:10
-
-
Save n8ebel/803804c29b073f94ae53187c55d8a538 to your computer and use it in GitHub Desktop.
A custom Kotlin delegate for initializing ViewDataBinding objects for Android databinding
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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