onCreateOptionsMenu does not get called in a fragment. I have to manually call setHasOptionsMenu(true)
in onCreatedView()
but this causes the item.itemId
be an empty String ""
in the onOptionsItemSelected()
and therefore i can’t detect which menu item was tapped.
I’m currently using this in a fragment:
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { super.onCreateOptionsMenu(menu, inflater) inflater.inflate(R.menu.menu_font_share, menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.menu_font_size_Btn -> { } R.id.menu_share_Btn -> { super.showShareSheet() } } return super.onOptionsItemSelected(item) }
Advertisement
Answer
Call super.onCreateOptionsMenu(menu,inflater)
after menu inflate
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.menu_font_share, menu) super.onCreateOptionsMenu(menu,inflater) }
This may more help Ref :: https://stackoverflow.com/a/15654039/11393354
try this,
@Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.menu_sample, menu); super.onCreateOptionsMenu(menu,inflater); }
And in onCreate
add this line to make the options appear in your Toolbar
setHasOptionsMenu(true);