@@ -34,11 +34,7 @@ object ViewBindingUtil {
34
34
fun <VB : ViewBinding > inflateWithGeneric (genericOwner : Any , layoutInflater : LayoutInflater ): VB =
35
35
withGenericBindingClass<VB >(genericOwner) { clazz ->
36
36
clazz.getMethod(" inflate" , LayoutInflater ::class .java).invoke(null , layoutInflater) as VB
37
- }.also { binding ->
38
- if (genericOwner is ComponentActivity && binding is ViewDataBinding ) {
39
- binding.lifecycleOwner = genericOwner
40
- }
41
- }
37
+ }.withLifecycleOwner(genericOwner)
42
38
43
39
@JvmStatic
44
40
fun <VB : ViewBinding > inflateWithGeneric (genericOwner : Any , parent : ViewGroup ): VB =
@@ -49,21 +45,31 @@ object ViewBindingUtil {
49
45
withGenericBindingClass<VB >(genericOwner) { clazz ->
50
46
clazz.getMethod(" inflate" , LayoutInflater ::class .java, ViewGroup ::class .java, Boolean ::class .java)
51
47
.invoke(null , layoutInflater, parent, attachToParent) as VB
52
- }.also { binding ->
53
- if (genericOwner is Fragment && binding is ViewDataBinding ) {
54
- binding.lifecycleOwner = genericOwner.viewLifecycleOwner
55
- }
56
- }
48
+ }.withLifecycleOwner(genericOwner)
57
49
58
50
@JvmStatic
51
+ @Suppress(" DEPRECATION" )
52
+ fun <VB : ViewBinding > getBindingWithGeneric (genericOwner : Any , view : View ): VB =
53
+ view.getTag(R .id.tag_view_binding) as ? VB ? : bindWithGeneric<VB >(genericOwner, view)
54
+ .also { view.setTag(R .id.tag_view_binding, it) }
55
+
56
+ @JvmStatic
57
+ @Deprecated(
58
+ " Use ViewBindingUtil.getBindingWithGeneric<VB>(genericOwner, view) instead." ,
59
+ ReplaceWith (" ViewBindingUtil.getBindingWithGeneric<VB>(genericOwner, view)" )
60
+ )
59
61
fun <VB : ViewBinding > bindWithGeneric (genericOwner : Any , view : View ): VB =
60
62
withGenericBindingClass<VB >(genericOwner) { clazz ->
61
63
clazz.getMethod(" bind" , View ::class .java).invoke(null , view) as VB
62
- }.also { binding ->
63
- if (genericOwner is Fragment && binding is ViewDataBinding ) {
64
- binding.lifecycleOwner = genericOwner.viewLifecycleOwner
65
- }
64
+ }.withLifecycleOwner(genericOwner)
65
+
66
+ private fun <VB : ViewBinding > VB.withLifecycleOwner (genericOwner : Any ) = apply {
67
+ if (this is ViewDataBinding && genericOwner is ComponentActivity ) {
68
+ lifecycleOwner = genericOwner
69
+ } else if (this is ViewDataBinding && genericOwner is Fragment ) {
70
+ lifecycleOwner = genericOwner.viewLifecycleOwner
66
71
}
72
+ }
67
73
68
74
private fun <VB : ViewBinding > withGenericBindingClass (genericOwner : Any , block : (Class <VB >) -> VB ): VB {
69
75
var genericSuperclass = genericOwner.javaClass.genericSuperclass
0 commit comments