How to add fragment specific menus in Android

You can show new menus from fragment by onCreateOptionsMenu method

First you need to setHasOptionsMenu(true) in onCreateView method as

 @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment,
                container, false);
        this.view = view;


        setHasOptionsMenu(true);


        return view;
    }

second you have to create menus.xml in res/menu/ folder

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">


    <item
        android:id="@+id/settings"
        android:icon="@drawable/settings_icon"
        android:orderInCategory="100"
        android:title="@string/settings"
        app:showAsAction="always" />


</menu>

And also you have to set menu in onCreateOptionsMenu method as

 @Override
    public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
        inflater.inflate(R.menu.menus, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }

If you want to replace menus with new menus then you just have to add menu.clear()  before inflating new menus as

@Override
    public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
        menu.clear(); 
        inflater.inflate(R.menu.menus, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }

Leave a Reply

Your email address will not be published. Required fields are marked *