• (笔记)Kotlin——Android封装ViewBinding之二 优化


     0. 在app模块的build.gradle文件中添加如下配置开启ViewBinding 

    1. android {
    2. .......
    3. viewBinding {
    4. enabled = true
    5. }
    6. }

    1. 新建一个Ext.kt文件 

    添加两个扩展函数,分别对应Activity和Fragment

    1. inline fun AppCompatActivity.viewBinding(crossinline bindingInflater: (LayoutInflater) -> T) =
    2. lazy(LazyThreadSafetyMode.NONE) {
    3. bindingInflater.invoke(layoutInflater)
    4. }
    5. inline fun Fragment.viewBinding(crossinline bindingInflater: (LayoutInflater, ViewGroup? , Boolean) -> T) =
    6. lazy(LazyThreadSafetyMode.NONE) {
    7. bindingInflater.invoke(layoutInflater, view?.parent as? ViewGroup, false)
    8. }

    2. Activity中使用

    BaseActivity

    1. public abstract class BaseActivity<VB : ViewBinding>(inflater: (LayoutInflater) -> VB) :
    2. AppCompatActivity() {
    3. protected val binding by viewBinding(inflater)
    4. override fun onCreate(savedInstanceState: Bundle?) {
    5. super.onCreate(savedInstanceState)
    6. setContentView(binding.root)
    7. initView()
    8. initData()
    9. }
    10. protected fun initView() {}
    11. protected fun initData() {}
    12. }

    继承自BaseActivity的子类 

    1. class VideoPlayerActivity : BaseActivity<ActivityVideoPlayerBinding>(ActivityVideoPlayerBinding::inflate),
    2. View.OnClickListener {
    3. override fun initView() {
    4. binding.play.setOnClickListener(this)
    5. }
    6. override fun onClick(p0: View?) {
    7. }
    8. }

    3. Fragment中使用

    1. abstract class BaseFragment<VB : ViewBinding>(inflater: (LayoutInflater, ViewGroup?, Boolean) -> VB)
    2. : Fragment() {
    3. protected val binding by viewBinding(inflater)
    4. override fun onCreateView(
    5. inflater: LayoutInflater,
    6. container: ViewGroup?,
    7. savedInstanceState: Bundle?
    8. ): View? {
    9. initView(binding.root, savedInstanceState)
    10. return binding.root
    11. }
    12. abstract fun initView(root: View, savedInstanceState: Bundle?)
    13. }

    继承自BaseFragment的子类

    1. class TestFragment : BaseFragment<FragmentTestBinding>(FragmentTestBinding::inflate) {
    2. override fun initView(root: View, savedInstanceState: Bundle?) {
    3. }
    4. }
  • 相关阅读:
    JlinkV9 修复相关
    【React】第十五部分 React-Router6
    flink实现kafka、doris精准一次说明
    NUUO摄像头远程命令执行漏洞复现 [附POC]
    Python——案例
    【MATLAB教程案例7】基于Gardner环的定时误差检测matlab仿真
    open3d 0.17.0的open3d.visualization.ViewControl类有bug
    go.mod 文件的作用
    thinkphp 自定义错误页面
    nuc980学习笔记7-设置开机自启动
  • 原文地址:https://blog.csdn.net/u011046452/article/details/134162245