Search code examples
androidmemory-leaksfragmenttoolbar

Toolbar inside Fragments is leaking


I have an app that has a separate toolbar for each Fragment. Then the app sets it into Activity with setSupportActionBar method. Apparently this causes Fragment layout to leak after onDestroyView.

What I have tried is

  1. setting activity.setSupportActionBar(null) which cause issues since Navigation library has following sequence of events: new Fragment is created and old calls onDestroyView. So putting the above code in onDestroyView causes the supportActiobBar to be null.

  2. considered having one toolbar which is not easy since requires major refactoring and this is not my personal project.

  3. setting toolbar to null. Doesn't work cause ViewBinding doesn't allow that.

The questions is - is there any other way to mitigate the memory leak in this case.


Solution

  • As per the Fragment-owned app bar documentation:

    When using a fragment-owned app bar, we strongly recommended using the Toolbar APIs directly. Do not use setSupportActionBar() and the Fragment menu APIs, which are appropriate only for activity-owned app bars.

    In most cases, you can rely solely on the Toolbar APIs like inflateMenu and skip setting setSupportActionBar() at all.