inline fun <reified T : ViewBinding> viewBinding() = ActivityViewBindingDelegate(T::class.java)
class ActivityViewBindingDelegate<T : ViewBinding>(private val bindingClass: Class<T>) : ReadOnlyProperty<Activity, T> {
private var binding: T? = null
@Suppress("UNCHECKED_CAST")
override fun getValue(thisRef: Activity, property: KProperty<*>): T {
binding?.let { return it }
val inflateMethod = bindingClass.getMethod("inflate", LayoutInflater::class.java)
val invokeLayout = inflateMethod.invoke(null, thisRef.layoutInflater) as T
thisRef.setContentView(invokeLayout.root)
return invokeLayout.also { this.binding = it }
}
}
viewbing代理
最新推荐文章于 2024-09-29 17:10:41 发布
该博客详细介绍了如何在Kotlin中实现ViewBinding,通过`inlinefun viewBinding()`函数简化了在Activity中绑定视图的过程。内容包括创建`ActivityViewBindingDelegate`类,利用反射机制调用`inflate`方法并设置内容视图,提供了一个便捷的视图绑定解决方案。


1548

被折叠的 条评论
为什么被折叠?



