Skip to content

Instantly share code, notes, and snippets.

@kirich1409
Last active June 27, 2021 19:24
Show Gist options
  • Save kirich1409/fefcebaa29a443fd9bee5d266ec737a1 to your computer and use it in GitHub Desktop.
Save kirich1409/fefcebaa29a443fd9bee5d266ec737a1 to your computer and use it in GitHub Desktop.
class FragmentViewBindingProperty<T : ViewBinding>(
private val viewBinder: ViewBinder<T>
) : ReadOnlyProperty<Fragment, T> {
private var viewBinding: T? = null
private val lifecycleObserver = BindingLifecycleObserver()
@MainThread
override fun getValue(thisRef: Fragment, property: KProperty<*>): T {
checkIsMainThread()
this.viewBinding?.let { return it }
val view = thisRef.requireView()
thisRef.viewLifecycleOwner.lifecycle.addObserver(lifecycleObserver)
return viewBinder.bind(view).also { vb -> this.viewBinding = vb }
}
private inner class BindingLifecycleObserver : DefaultLifecycleObserver {
private val mainHandler = Handler(Looper.getMainLooper())
@MainThread
override fun onDestroy(owner: LifecycleOwner) {
owner.lifecycle.removeObserver(this)
viewBinding = null
}
}
}
/**
* Create new [ViewBinding] associated with the [Fragment][this]
*/
@Suppress("unused")
inline fun <reified T : ViewBinding> Fragment.viewBinding(): ReadOnlyProperty<Fragment, T> {
return FragmentViewBindingProperty(DefaultViewBinder(T::class.java))
}
@yogithesymbian
Copy link

can you re-edit with import sytnx ? because i have Unresolved reference: ViewBinder and Unresolved reference: checkIsMainThread
in my gradle has set buildFeatures {
dataBinding true
viewBinding true
}

@kirich1409
Copy link
Author

Create issue with sample project where the issue is reproducible

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment