The action bar menu items will change based on the tab selection. This menu contains some of the common menu items and the tab specific menu items.The below image illustrates this better than words.
Why do you need to add action items from Fragments?
In the above image shows that the menu contains common items like Search, Settings, and Status and the fragment specific options like call, chat, contacts icons. So you need to add the common menu items in the parent activity menu and fragment specific menu items from within your fragments.
How to add action items from Fragments?
Create the menu files, as usual, then you need to specify that the fragment contains menu using the below snippet.
Now you need to inflate the menu for this fragment using OnCreateOptionsMenu, just override this native method into your fragment and initialize the menu.
How to handle clicks event ?
As usual, override OnOptionsItemSelected method for handling click events of the menu items. OnOptionsItemSelected is called whenever an item in your options menu is selected.
How to change the order of the items ?
Now most of the peoples have the same doubt, We are using the global menu from the activity so OnCreateOptionsMenu in the parent activity executes first then only the child fragment, then how to change the order of the items.
It’s so simple Android provides the attribute called orderInCategory. You can re-order the menu items using this attribute by specifying the integer values. The menu items are arranged from left to right in ascending order based on the given integer value.
I made a simple sample app using this concept, it’s over on GitHub if you want to check it out.
Feel free to comment and share, keep watching this space get more updates on Android Stuff!
Latest posts by Jaison Fernando (see all)
- How to create face detector using Firebase MLKit? - November 29, 2018
- How to create a barcode scanner using Firebase MLKit? - November 9, 2018
- How to update your app using Firebase Remote Config? - October 20, 2018