1.module所在build.gradle添加配置启用ViewBinding + 代码混淆
android{
...
viewBinding {
enabled = true
}
}
因封装使用了反射,所以混淆规则需将反射调用方法禁止混淆
# ViewBinding
-keepclassmembers class * implements androidx.viewbinding.ViewBinding {
public static * inflate(android.view.LayoutInflater);
}
2.封装BaseActivity(关键代码段)
abstract class BaseActivity<VB : ViewBinding>: AppCompatActivity(){
private var _bind: VB? = null
protected val mViewBinding get() = _bind!!
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
try {
val vmClass = (this.javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[0] as Class<VB>
val method: Method = vmClass.getMethod("inflate", LayoutInflater::class.java)
_bind = method.invoke(null, layoutInfla