-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathViewBinding.kt
28 lines (24 loc) · 1.02 KB
/
ViewBinding.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// ViewBinding delegate for Fragments
// Use example: someFragmentBindig by bindFragment<SomeFragmentBinding>(SomeFragmentBinding::bind)
class bindFragment<T : ViewBinding>(
private val viewBinder: (View) -> T
) : ReadOnlyProperty<Fragment, T> {
private var binding: T? = null
private val bindingLifecycleObserver = BindingLifecycleObserver()
override operator fun getValue(thisRef: Fragment, property: KProperty<*>): T {
this.binding?.let { return it }
val fragmentView = thisRef.requireView()
thisRef.viewLifecycleOwner.lifecycle.addObserver(bindingLifecycleObserver)
return viewBinder.invoke(fragmentView).also {
this.binding = it
}
}
private inner class BindingLifecycleObserver : DefaultLifecycleObserver {
private val mainHandler = Handler(Looper.getMainLooper())
@MainThread
override fun onDestroy(owner: LifecycleOwner) {
owner.lifecycle.removeObserver(this)
mainHandler.post { binding = null }
}
}
}