Search code examples
androidmemory-leaksandroid-viewbinding

ViewBinding - do we need to remove clicklisteners to avoid memory leaks?


When using Android ViewBinding do you then have to explicitly remove clickListeners to avoid memory leaks or is that all handlede with releasing the binding?

binding.button.setOnClickListener { }

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

Solution

  • Memory leak appears only if you adding Fragment instance to the backstack without clearing that Fragment view fields in Fragment.onDestroyView() callback.

    Yes you should do it manually, ViewBinding do not have desired implementation. If you do not want to do it manually you can write your own delegate that do it automatically or use well designed library.