Search code examples
androidandroid-activity

What is the correct place to add or remove ViewTreeObserver listeners?


I can add the Listener to OnCreate or add it to OnResume and remove it OnPause. Is there a benefit of using one or the other implementation?


Solution

  • If we're talking of activity then you need to register the listener in the ViewTree in onCreate() method as the view is not measured yet and remove it in onDestroy().

    In fragments, it should be registered in onViewCreated() and removed in onDestroyView()