android {
...
buildFeatures {
viewBinding true
}
}
abstract class BaseActivity : AppCompatActivity() {
private var binding: ViewBinding? = null
@Suppress("UNCHECKED_CAST")
inline fun <reified T : ViewBinding> viewBinding(): Lazy<T> {
return object : Lazy<T> {
private var binding: T? = null
override val value: T
get() = binding ?: createBinding().also { binding = it }
override fun isInitialized() = binding != null
private fun createBinding(): T {
val inflateMethod = T::class.java.getMethod("inflate", LayoutInflater::class.java)
val invokeLayoutInflate = inflateMethod.invoke(null, layoutInflater) as T
setContentView(invokeLayoutInflate.root)
return invokeLayoutInflate
}
}
}
override fun onDestroy() {
super.onDestroy()
binding = null
}
}
使用 如下:
private val binding by viewBinding<ActivityMainBinding>()