I am trying to add an item to the options menu from a group of fragments.
I have created a new MenuFragment
class and extended this for the fragments I wish to include the menu item in. Here is the code:
Java:
public class MenuFragment extends Fragment { MenuItem fav; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { fav = menu.add("add"); fav.setIcon(R.drawable.btn_star_big_off); } }
Kotlin:
class MenuFragment : Fragment { lateinit var fav: MenuItem override fun onCreate(savedInstanceState: Bundle) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { fav = menu.add("add"); fav.setIcon(R.drawable.btn_star_big_off); } }
For some reason the onCreateOptionsMenu
appears not to run.
if you are using custom toolbar or ActionBar and you want to get reference of your toolbar/action bar from Fragments then you need to first get instance of your Main Activity from Fragment's onCreateView Method like below. ImageView vRightBtn = activity. toolbar. findViewById(R.
You need to use menu. clear() before inflating menus. This is correct when you want different menus in different fragments and you are adding fragments instead of replacing them.
When you click the hide button to hide the fragment. The fragment menu items disappear from the action bar also. You can also click back menu to exit the fragment and the activity.
onCreateOptionsMenu() is called by the Android runtime when it need to create the option menu.
Call the super method:
Java:
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { // TODO Add your menu entries here super.onCreateOptionsMenu(menu, inflater); }
Kotlin:
override fun void onCreate(savedInstanceState: Bundle) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { // TODO Add your menu entries here super.onCreateOptionsMenu(menu, inflater) }
Put log statements in the code to see if the method is not being called or if the menu is not being amended by your code.
Also ensure you are calling setHasOptionsMenu(boolean)
in onCreate(Bundle)
to notify the fragment that it should participate in options menu handling.
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