Activity
open class BaseActivity<T:ViewBinding>: AppCompatActivity() {
lateinit var binding:T
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val cls = (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[0] as Class<T>
binding = cls.getMethod("inflate", LayoutInflater::class.java).invoke(null, LayoutInflater.from(this)) as T
setContentView(binding.root)
}
}
class MainActivity:BaseActivity<ActivityMainBinding>() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding.tv.text = "hehe"
}
}
Fragment
open class BaseFragment<T: ViewBinding> : Fragment() {
private var _binding:T? = null
val binding get() = _binding!!
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val cls = (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[0] as Class<T>
_binding = cls.getMethod("inflate", LayoutInflater::class.java, ViewGroup::class.java, Boolean::class.java).invoke(null, LayoutInflater.from(requireActivity()), container, false) as T
return binding.root
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
class HomeFragment:BaseFragment<FragmentHomeBinding>() {
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
binding.tv.text = "hehe"
}
}
View
class XxxView : ConstraintLayout {
lateinit var binding:XxxxxBinding
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
init {
val root = inflate(context, R.layout.xxx, this)
binding = XxxxxBinding.bind(root)
initView()
}
private fun initView() {
binding.tv.text = "hehe"
}
混淆
-keep class * implements androidx.viewbinding.ViewBinding
-keepclassmembers class * implements androidx.viewbinding.ViewBinding { public static ** inflate(...); public static ** bind(***); }
网友评论