18
18
19
19
package com.dylanc.viewbinding
20
20
21
+ import android.os.Handler
22
+ import android.os.Looper
21
23
import android.view.LayoutInflater
22
24
import androidx.databinding.ViewDataBinding
23
25
import androidx.fragment.app.Fragment
@@ -27,6 +29,8 @@ import androidx.viewbinding.ViewBinding
27
29
import kotlin.properties.ReadOnlyProperty
28
30
import kotlin.reflect.KProperty
29
31
32
+ enum class Method { BIND , INFLATE }
33
+
30
34
inline fun <reified VB : ViewBinding > Fragment.binding () =
31
35
FragmentBindingProperty (VB ::class .java)
32
36
@@ -47,29 +51,23 @@ class FragmentBindingProperty<VB : ViewBinding>(private val clazz: Class<VB>) :
47
51
48
52
class FragmentInflateBindingProperty <VB : ViewBinding >(private val clazz : Class <VB >) : ReadOnlyProperty<Fragment, VB> {
49
53
private var binding: VB ? = null
54
+ private val handler by lazy { Handler (Looper .getMainLooper()) }
50
55
51
- @Suppress(" UNCHECKED_CAST" )
52
56
override fun getValue (thisRef : Fragment , property : KProperty <* >): VB {
53
57
if (binding == null ) {
54
58
try {
59
+ @Suppress(" UNCHECKED_CAST" )
55
60
binding = (clazz.getMethod(" inflate" , LayoutInflater ::class .java).invoke(null , thisRef.layoutInflater) as VB )
56
61
.also { binding -> if (binding is ViewDataBinding ) binding.lifecycleOwner = thisRef.viewLifecycleOwner }
57
62
} catch (e: IllegalStateException ) {
58
63
throw IllegalStateException (" The property of ${property.name} has been destroyed." )
59
64
}
60
65
thisRef.viewLifecycleOwner.lifecycle.addObserver(object : DefaultLifecycleObserver {
61
66
override fun onDestroy (owner : LifecycleOwner ) {
62
- if (thisRef is BindingLifecycleOwner ) thisRef.onDestroyViewBinding(binding!! )
63
- binding = null
67
+ handler.post { binding = null }
64
68
}
65
69
})
66
70
}
67
71
return binding!!
68
72
}
69
73
}
70
-
71
- enum class Method { BIND , INFLATE }
72
-
73
- interface BindingLifecycleOwner {
74
- fun onDestroyViewBinding (destroyingBinding : ViewBinding )
75
- }
0 commit comments