I have a single activity android app, when the first fragment loads the toolbar doesn't show the menuItem
but it does show the title. If I navigate to any other fragment, then back to the home fragment it works as expected.
I'm setting up the toolbar in the MainActivity
as follows
@AndroidEntryPointclass MainActivity : AppCompatActivity(), MenuHost { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setupToolbar() } private fun setupToolbar() { val toolbar = findViewById<Toolbar>(R.id.toolbar) setSupportActionBar(toolbar) val host = supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment val navController = host.navController val appBarConfiguration = AppBarConfiguration(setOf(R.id.homeFragment)) toolbar.setupWithNavController(navController, appBarConfiguration) }}
Then in the HomeFragment I have something similar
private fun setupToolbar() { val mainActivity = requireActivity() as MainActivity val mainToolbar = mainActivity.findViewById<MaterialToolbar>(R.id.toolbar) // Clear previous menu items mainToolbar.menu.clear() // Set up toolbar mainToolbar.inflateMenu(R.menu.top_app_bar) mainToolbar.setOnMenuItemClickListener { menuItem -> when (menuItem.itemId) { R.id.more -> { findNavController().navigate(R.id.action_to_preferenceFragment) } } false }}
Where this is being called in both onViewCreated
and onResume
.
where have I gone wrong here with getting the menu items showing up in the first load of the HomeFragement
?
Edit: By adding these two methods on the fragment it solves my issue
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true)}override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.top_app_bar, menu) super.onCreateOptionsMenu(menu, inflater)}
However they're apparently deprecated and reading the deprecation description they shouldn't be required as I'm using the MenuHost
but perhaps I'm doing that wrong?