Android 实现对viewbinding的封装

柴辰阳
2023-12-01

1.build.gradle文件中启用

android {
...
    buildFeatures {
        viewBinding true
    }
}

2.封装

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
    }
}

3.继承基类BaseActivity后

使用 如下:

 private val binding by viewBinding<ActivityMainBinding>()
 类似资料: