Home > OS >  Android: Leak in toolbar
Android: Leak in toolbar

Time:10-01

My app is set up to have a unique toolbar for each Fragment. In one particular fragment, I want to override the Navigate Up or Back button in the toolbar to give a warning to the user to confirm their intention.

I originally asked this question here and found that by changing my original code to using setSupportActionBar to implement the toolbar, I was able to maintain my unique toolbar for the fragment and ovveride the Navigate Up button.

However, I just noticed that whenever I back out of that fragment that uses setSupportActionBar for the toolbar, I get a memory leak (same as the problem found by this user). I confirmed this by commenting out the line that sets up the actionbar and saw that the leak had disappeared.

How can I maintain my unique toolbar, override the Navigate Up button and avoid this memory leak?

CodePudding user response:

However, I just noticed that whenever I back out of that fragment that uses setSupportActionBar for the toolbar, I get a memory leak

You can try to eleminate this by setSupportActionBar(null) when this particular fragment is destroyed:

override fun onDestroy() {
    super.onDestroy()
    (requireActivity() as AppCompatActivity).setSupportActionBar(null)
}

Java:

// In the fragment
@Override
public void onDestroy() {
    super.onDestroy();
    ((AppCompatActivity) requireActivity()).setSupportActionBar(null);
}
  • Related