This tutorial shows you how to add action items to the ActionBar from within your Fragments. In my previous post, you have seen that every tab in the viewpager connected with the fragment.
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!
Jaison Fernando
Latest posts by Jaison Fernando (see all)
- Phone number auth using Firebase Authentication SDK - March 20, 2020
- Password-less email auth using Firebase Authentication SDK - March 9, 2020
- How to use SharedPreferences API in Android? - February 10, 2020