If I have one activity with one fragment, fragment1, and use the navigation component to navigate from fragment1 to fragment2 after setting the supportActionBar to null in onDestroyView, onCreateOptionsMenu
is not called even if setHasOptionsMenu(true)
is called in onCreate.
fragment1.kt:
...
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
(requireActivity() as AppCompatActivity).setSupportActionBar(toolbar) //kotlin view extension to the Toolbar in fragment1.xml
view.findViewById<Button>(R.id.without_toolbar_button).setOnClickListener {
findNavController().navigate(R.id.action_FirstFragment_to_SecondFragment)
}
}
override fun onDestroyView() {
super.onDestroyView()
(requireActivity() as AppCompatActivity).setSupportActionBar(null)
}
...
fragment2.kt:
...
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
(requireActivity() as AppCompatActivity).setSupportActionBar(toolbar)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
Toast.makeText(requireActivity(), "onCreateOptionsMenu called!", Toast.LENGTH_SHORT).show() //this is never called if navigation occurs from fragment1 to this fragment.
super.onCreateOptionsMenu(menu, inflater)
}
...
fragment1.xml & fragment2.xml:
...
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content" ... />
...
The toast is never called. A full demo project demonstrating this can be found and cloned on github.
"I had problems with fragments remaining in memory. After adding setSupportActionBar(null), the fragments were garbage collected." See this answer from a thread about memory leaks.