androidkotlinobserversandroid-viewtreeobserver

Android -How to Remove ViewTreeObserver GlobalLayoutListener with .removeOnGlobalFocusChangeListener


How do I remove a viewTreeObserver? There are 3 different removeOnGlobalFocusChangeListener callbacks

enter image description here

class MyFragment: Fragment() {

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
    
        binding.root.viewTreeObserver.addOnGlobalLayoutListener {
            doSomething()
        }
    }
    
    override fun onDestroy() {
        super.onDestroy()

        // I don't know if this is the correct one to call
        binding.root.viewTreeObserver.removeOnGlobalFocusChangeListener { oldFocus, newFocus ->  }
    }
}

Solution

  • you should keep reference to this listener (when created in onViewCreated) and release it in onViewDestroyed using removeOnGlobalFocusChangeListener(..) method and passing listener as victim. or earlier if doSomething() call isn't necessary to be called so often (once?)

    var globalListener: ViewTreeObserver.OnGlobalLayoutListener? = null
    
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
    
        globalListener = ViewTreeObserver.OnGlobalLayoutListener { doSomething() }
        binding.root.viewTreeObserver.addOnGlobalLayoutListener(globalListener)
    }
    
    override fun onDestroy() {
        globalListener?.let { binding.root.viewTreeObserver.removeOnGlobalFocusChangeListener(it) }
        globalListener = null
        super.onDestroy()
    }