open class BaseSettingsActivity<T : ViewBinding> : BaseActivity() {
@Suppress("UNCHECKED_CAST")
protected val binding by lazy {
var superCls = javaClass.genericSuperclass
while (superCls !is ParameterizedType) {
superCls = (superCls as Class<*>).genericSuperclass
}
((superCls as ParameterizedType).actualTypeArguments[0] as Class<*>).getDeclaredMethod(
"inflate", LayoutInflater::class.java
).invoke(null, layoutInflater) as T
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
}
}
使用
class TestActivity: BaseSettingsActivity<ActivityMainBinding>() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
}