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
Get Android Application Development Cookbook - Second Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.