Add toolbar menu to Fragment

This kind of demand is often met in the application:

There are different fragments in an Activity, such as MainActivity. Two different fragments require different toolbar s and menu s.

How to customize Fragment's toolbar?

1. Add toolbar to the xml of fragment;

2. Add setHasOptionsMenu(true) to onCreate method of fragment;

@Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);//Add this sentence to the menu
    }

3. Initialize toolbar

mToolbarContact = view.findViewById(R.id.tool_bar_contact);
((AppCompatActivity) getActivity()).setSupportActionBar(mToolbarContact);

4. Override onCreateOptionsMenu:

 @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        //menu.clear(); / / this sentence is useless. You don't need to add it
        inflater.inflate(R.menu.menu_contacts, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }

5. Override onoptionsiteselected:

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.menu_add_contact) {
            T.showToastBro(getActivity(), item.getTitle().toString());
        }
        if (id == R.id.menu_nearby_businesses) {
            T.showToastBro(getActivity(), item.getTitle().toString());
        }
        return super.onOptionsItemSelected(item);
    }

Then we find that the menu of fragment overlaps with the menu of activity.

  • The problem is in step 3, to change to:

mToolbarContact = view.findViewById(R.id.tool_bar_contact);
mToolbarContact.inflateMenu(R.menu.menu_contacts);
  • Then it is found that the click event of menu is not corresponding. Even if setHasOptionsMenu(true) has been added;

The fourth and fifth do not need to be rewritten. To implement click event in toolbar code

mToolbarContact = view.findViewById(R.id.tool_bar_contact);
mToolbarContact.inflateMenu(R.menu.menu_contacts);
mToolbarContact.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                int id = item.getItemId();
                if (id == R.id.menu_add_contact) {
                    T.showToastBro(getActivity(), item.getTitle().toString());
                }
                if (id == R.id.menu_nearby_businesses) {
                    T.showToastBro(getActivity(), item.getTitle().toString());
                }
                return true;
            }
        });

Solve!

Keywords: Fragment xml

Added by amarquis on Tue, 24 Dec 2019 21:17:23 +0200