继承 Lazy 方式
实现代码
fun <T : ViewBinding> AppCompatActivity.binding(inflate: (LayoutInflater) -> T): Lazy<T> { return MainLazy(this, inflate) } class MainLazy<T : ViewBinding>( val activity: AppCompatActivity, val inflate: (LayoutInflater) -> T ) : Lazy<T> { var cache: T? = null override val value: T get() { if (cache == null) { cache = inflate(activity.layoutInflater) } return cache!! } override fun isInitialized(): Boolean = cache != null } 复制代码
使用方式
val binding: ActivityMainBinding by binding(ActivityMainBinding::inflate) 复制代码
lazy 关键字方式
实现代码
fun <T : ViewBinding> AppCompatActivity.bindingByLazy(inflate: (LayoutInflater) -> T)= lazy { inflate(layoutInflater).apply { } } 复制代码
使用方式
val binding: ActivityMainBinding by bindingByLazy(ActivityMainBinding::inflate) 复制代码