Add onOptionsItemSelected calling in Fragment

In Fragment you have to call setHasOptionsMenu(true)

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
    ...
}

Then suppose you have to handle menu_item_to_handle_in_fragment item click

For Fragment class

  @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {

        case R.id.menu_item_to_handle_in_fragment:
            // Do onlick on menu action here
            return true;
        }
    return false;
}

For Activity class

 @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            switch (item.getItemId()) {

            case R.id.menu_item_to_handle_in_fragment:
                return false;
            }
        return false;
    }

You need to add setHasOptionMenu(true) in your onCreate of fragment.
When you add this option the fragment lifecycle will calls the onCreateOptionMenu() and onOptionItemSelected().

Follow this steps:

  • Add setHasOptionsMenu(true) method in onCreate() of your Fragment.

  • Override onCreateOptionsMenu(Menu menu, MenuInflater inflater) and onOptionsItemSelected(MenuItem item) methods in your Fragment.

  • Inside your onOptionsItemSelected(MenuItem item) Activity's method, make sure you return false when the menu item action would be implemented in onOptionsItemSelected(MenuItem item) Fragment's method.