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"
/>
The best way to do it :
1. Find toolbar in Activity and set it as supportActionBar.
2. Then It will be a piece of cake to handle option menus for different fragments over a same Activity. Do following things in each fragment as you want:
In OnCreateView Method call
And Lastly,
And to manage menu items click, we have onOptionsItemSelected:
Below are the steps to show different menu options with different fragments.
Step1: Call setHasOptionsMenu(true)
Step2: Inflate your fragment related option menu items.
Override
onCreateOptionsMenu
method in your every fragment.I had the same issue and I wanted to replace the toolbar menu accordingly to the fragment displayed.
The problem I'm now facing is that the menu is added to the previous one.
In order to show only the menu for the fragment, I suggest:
Hope it'll help.
This is how to create menu dynamically: http://www.101apps.co.za/index.php/articles/using-toolbars-in-your-apps.html
Edited: