(笔记)Kotlin——Android封装ViewBinding

另一篇优化后的ViewBinding的文章 (推荐)

​​​​​​http://t.csdnimg.cn/gUi43icon-default.png?t=N7T8http://t.csdnimg.cn/gUi43

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


android {
    .......

    viewBinding {
        enabled = true
    }

}

二、Activity

1. BaseActivity

abstract class BaseActivity : AppCompatActivity() {

    // 当调用bingding的时候 就会调用getViewBinding方法, 由于使用了lazy,所以该方法只会调用一次
    protected val binding by lazy { getViewBinding() }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        initView()
        initData()
    }

    protected abstract fun initData()

    protected abstract fun initView()

    protected abstract fun getViewBinding(): VB

}

2. MainActivity

class MainActivity : BaseActivity() {

    override fun initView() {
        binding.textView.text = "封装ViewBinding"
    }

    override fun initData() {

    }

    override fun getViewBinding() = ActivityMainBinding.inflate(layoutInflater)

}

三、Fragment

1. BaseFragment

由于可能会产生内存泄漏问题,在Fragment界面销毁的时候,会回调onDestroyView()这个方法中,在这个方法中将_binding对象置为null

abstract class BaseFragment : Fragment() {

    private var _binding: VB? = null

    protected val binding
        get() = _binding!!

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = getViewBinding(inflater)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()
    }

    protected abstract fun initView()

    protected abstract fun getViewBinding(inflater: LayoutInflater): VB

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

}

2. LoginFragment

class LoginFragment : BaseFragment() {

    override fun initView() {
        binding.textView.text = "封装了ViewBinding"
    }

    override fun getViewBinding(inflater: LayoutInflater) =
        FragmentLoginBinding.inflate(inflater, null, false)
}

希望能帮到你

你可能感兴趣的:(android,android,android,studio,ide)