Forked from kirich1409/FragmentViewBindingProperty.kt
Created
August 23, 2020 19:16
-
-
Save Bloody-Badboy/5cff76ac17a619a46e8410b95555cb36 to your computer and use it in GitHub Desktop.
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 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)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment