I have given toolbar for each fragment in my app.
Following is code in the fragment to set toolbar. setToolbar
is a method in Activity
which is called from fragment using the interface.
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Toolbar toolbar = view.findViewById(R.id.toolbar);
if (mListener != null) {
mListener.setToolbar(toolbar);
}
}
Now since I am not removing toolbar when the fragment is destroyed it is causing a memory leak. I want to know where should I remove the toolbar fragment and how.
Any idea where and how should I release toolbar which is in the fragment?
As per my previously asked question Can I have toolbar for each fragment separately. How to handle navigation drawer I was told I can have a toolbar in each fragment but now I am facing memory leak.
Instead of creating toolbar for each fragment separately, create a single toolbar in the parent activity of those fragments.
If you are concerned about menu options in each fragment, then no need to worry. Just write setHasOptionsMenu(true)
inside onCreateView
method of each fragment. Also override onCreateOptionsMenu
and onOptionsItemSelected
in each fragment.
Activity toolbar will reflect the changes in menu options automatically.
NOTE: Always generate an activity from the template provided by Android Studio. It will save you both time and energy. You can always remove all the boiler plate code which you deem to be unnecessary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With