Modifying menus and menu items during runtime
Though it's been stated many times, it's considered the "best" programming practice to create UI in XML rather than in Java. There are still times when you may need to do it in code. This is especially true if you wanted a menu item to be visible (or enabled) based on some external criteria. Menus can also be included in resource folders, but there are times when you need code to perform the logic. One example might be if you wanted to offer an upload menu item only if the user is logged in to your app.
In this recipe, we will create and modify the menu only through code.
Getting ready
Create a new project in Android Studio and call it RuntimeMenu
using the default Phone & Tablet option. Select the Empty Activity option when prompted to add an Activity. Since we will create and modify the menu completely in code, we will not need to create a res/menu
directory.
How to do it...
To start, we will add string resources for our...