Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Toolbar Adding Menu Items for different fragments

I have a toolbar as well as a navigation drawer. When I start my app, the toolbar and navigation drawer are created. When I click items in the navigation drawer, it starts new fragments and keeps the same toolbar. How do I basically add menu items to the toolbar such as search, add, edit when I start specific fragments? I don't want them at the start of the program, but created dynamically. Also, how would I be able to click these buttons and have them start other fragments. I want it so in one fragment, the edit button in the toolbar does a specific thing compared to the edit button in another fragment. Thanks!

Menu_toolbar:

<?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/edit"     android:orderInCategory="1"     android:title="Edit"     app:showAsAction="always"     android:icon="@drawable/pencil_icon"/> <item android:id="@+id/add"     android:orderInCategory="1"     android:title="Add"     app:showAsAction="always"     android:icon="@drawable/plus_icon"/> 

Toolbar:

<?xml version="1.0" encoding="utf-8"?> <android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="55dp" android:background="#10a1ff" android:title="Home" /> 
like image 789
Joe Eigi Avatar asked Jun 09 '15 01:06

Joe Eigi


People also ask

How do I inflate a menu in fragment?

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.

How do we hide the menu on toolbar in one fragment?

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.


1 Answers

Add similar code to your fragments:

@Override public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {     View v = inflater.inflate(R.layout.library_fragment, parent, false);     setHasOptionsMenu(true);     return v; }   @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {    inflater.inflate(R.menu.your_menu_xml, menu);    super.onCreateOptionsMenu(menu, inflater); } 

This way you can customize the menu for your fragments.

like image 147
Gundu Bandgar Avatar answered Oct 27 '22 01:10

Gundu Bandgar