Developing a high-quality user interface is not just about drawing beautiful buttons, but also providing intuitive navigation. In the ecosystem, the de facto standard for placing basic actions and settings is the top bar of the application, often called Android The de facto standard for placing basic actions and settings is the top bar of the application, often called Action Bar or Toolbar. Correct implementation of this element significantly improves the usability of your product, allowing the user to instantly find the necessary functions without unnecessary clicks.

In the development environment Android Studio the process of creating menus has become more structured and logical thanks to the use of resource files XML. This allows you to separate the visual part from the business logic, which makes it easier to maintain the code and adapt it to different device configurations. In this article we will analyze all the stages: from creating a resource file to processing clicks on menu items in code Kotlin or Java.

You will learn how to add icons, configure the display of elements in a drop-down list or on the action bar, and also how the system reacts to screen rotation. Understanding these mechanisms is critical for any developer who wants to create professional applications that follow the guidelines Material Design.

Preparing resources and creating an XML file

The first step in the process is to create a special directory to store menu resources. In the Android Studio project structure, go to the app/src/main/resdirectory. If a folder with the name menu is not there yet, you need to create it manually: right-click on the folder res, select New โ†’ Directory and name it menu. This is where all the files that describe the structure of your navigation interface will be stored.

After creating the directory, add a new menu resource file to it. To do this, right-click on the folder menu, select New โ†’ Menu Resource File. In the dialog box that opens, enter the file name, for example, main_menu.xml. The system will automatically generate the basic structure of the XML document with the root element <menu>. This file will become a container for all the items that you plan to place on the screen.

Inside the root tag <menu> elements are added <item>, each of which represents a separate item. For each element, it is necessary to define a unique identifier through the attribute android:id, a title through android:title and, if necessary, an icon through android:icon. xml, and the icons in a folder drawableto keep the code clean and make it easier to localize the application into other languages.

๐Ÿ’ก

Use vector assets (Vector Drawables) for menu icons instead of PNG bitmaps. They take up less space and scale without loss of quality on screens with any resolution.

Particular attention should be paid to the attribute app:showAsAction, which controls the behavior of the element on the action bar. It can take the following values: ifRoom (show if there is space), never (always hide in the drop-down menu) or always (always show in the panel, if possible). The combination of these parameters allows you to flexibly control how your menu will look on smartphones with small screens and on tablets.

Integrating the menu into an Activity or Fragment

Once the XML file is ready, it needs to be associated with a specific application screen. In modern Android architecture, this is done by overriding a method onCreateOptionsMenu within a class Activity or Fragment. This method is called automatically by the system when you first create an interface, giving you the opportunity to โ€œinflateโ€ your XML file into a ready-made menu object.

Internally, the method onCreateOptionsMenu uses an object MenuInflaterthat converts the description from XML into real Java or Kotlin objects. The code looks concise: you call the inflatemethod, passing it the resource ID of your menu file and the Menuobject to which you want to add the elements. The return value of the method should be trueto inform the system that the menu was created successfully and should be displayed to the user.

override fun onCreateOptionsMenu(menu: Menu): Boolean {

menuInflater.inflate(R.menu.main_menu, menu)

return true

}

If you are working with Fragment, the logic remains almost identical, but there is an important nuance: you must explicitly indicate that the fragment will participate in creating the menu. To do this, in the method onCreate of the fragment you need to call setHasOptionsMenu(true). Without this line of code, the method onCreateOptionsMenu inside the fragment simply will not be called by the system, and your menu will remain invisible to the user, which often causes confusion among novice developers.

โ˜‘๏ธ Integrating a menu into the project

Done: 0 / 5

Processing clicks on menu items

Creating a visual part is only half the battle. For an application to become interactive, it must respond to user actions. To do this, the onOptionsItemSelectedmethod is overridden, which is triggered every time the user selects an element from the list. This method is passed an object MenuItemcontaining information about what exactly was clicked.

Inside the method onOptionsItemSelected the construction when (in Kotlin) or switch (in Java) is usually used to check the identifier of the clicked element. By comparing item.itemId with the IDs that you specified in the XML file (for example, R.id.action_settings), you can execute the corresponding code: open a new window, show a settings dialog, or run a search. This is a standard event handling pattern in Android.

Don't forget to return true after processing the event if you have fully processed the click. If none of the items fit the conditions, you should call the superclass super.onOptionsItemSelected(item)method to pass the event further along the chain. This ensures that system functions such as the back button or standard controls work correctly.

What if onOptionsItemSelect does not fire?

Make sure you return true in the onCreateOptionsMenu method. If you return false there, the system will consider that the menu has not been created and will not track clicks on it. Also check if your menu is not overlapping another View with high focus priority.

Working with icons and grouping elements

The visual component of the menu plays a key role in the perception of the application. To add icons, use the attribute android:icon inside the tag item. It is recommended to use resources from the library Material Icons, which can be easily added through a vector asset in Android Studio. This ensures a consistent style and clarity of the image at any pixel density (dpi).

Menu elements can be combined into groups using the tag <group>. Grouping is useful when you need to apply common properties to several items at once, for example, making them all visible or invisible through code, or specifying a general sort order. The attribute android:checkableBehavior within a group allows you to implement the behavior of radio buttons (only one is selected) or checkboxes (several can be selected) for menu items.

The display order of elements is controlled by the attribute android:orderInCategory. Elements with a lower numeric value for this attribute will appear further to the left (or higher in the dropdown list). If you want the search button to always be first, give it a value of 1 and the settings button a value of 100. This gives you full control over the layout of the interface without being strictly tied to the XML writing order.

Attribute Description Example value
android:id Unique identifier of the element @+id/action_search
android:title Text name of the item @string/settings
app:showAsAction Display rule on the panel ifRoom|withText
android:icon Graphic image @drawable/ic_save
android:orderInCategory Element sorting order 10
๐Ÿ“Š What language do you use for Android development?
Kotlin
Java
C++
Other

Dynamic control of menu visibility

Situations often arise when the menu composition must change depending on the state of the application. For example, the "Edit" button should appear only when the user has selected an object, or the "Logout" item should be hidden if the user is not yet authorized. To solve such problems, the method is used onPrepareOptionsMenu.

This method is called by the system every time before the menu is displayed, which allows you to update its state in real time. Inside onPrepareOptionsMenu you get an object Menu and can find specific elements by their ID using the findItemmethod. Then you can call methods setVisible(false), setEnabled(false) or setTitle, changing the properties of elements on the fly.

If you need to force a menu refresh outside of the standard lifecycle (for example, after downloading data from the network has finished), use the invalidateOptionsMenumethod. It signals to the system that the current menu is out of date and needs to be redrawn, which will cause it to be called again onPrepareOptionsMenu. This is a powerful tool for creating a responsive interface that responds to user actions instantly.

โš ๏ธ Warning: Do not perform heavy calculations or network queries inside the method onPrepareOptionsMenu. This method can be called very often, and blocking the main thread will cause the interface to freeze and an ANR (Application Not Responding) error to appear.

Creating a context menu and pop-up windows

In addition to the standard main menu, in Android there are context menus that appear when you long press on a list item or (View). They are intended for actions specific to the selected object. Registration of such a menu is carried out through the registerForContextMenu(view)method, and selection processing is carried out through onContextItemSelected.

Another popular pattern is the use of PopupMenu. This is a pop-up menu that is tied to a specific view on the screen, such as a button with three dots. It is created programmatically through the class PopupMenu, inflated from the same XML resource and displayed by calling the method show. This is a great way to unload the main action bar and hide secondary functions.

To implement a pop-up menu, you need to create a listener for clicks on your trigger button. Inside the click handler, the object PopupMenuis initialized, the context and the binding to the view are specified. After inflating the menu, you need to install a click listener (setOnMenuItemClickListener) that will handle user selections similarly to the main menu.

๐Ÿ’ก

PopupMenu is ideal for secondary actions that do not deserve a place in the main Action Bar, but should be easily accessible in the context of a specific interface element.

โš ๏ธ Attention: Android interfaces are constantly evolving. Some classic Action Bar techniques may be deprecated in favor of newer components, such as the TopAppBar from the Material Components library. Always check the official Google documentation when starting a new project to ensure you are using the most up-to-date and supported solutions.

Frequent errors and interface debugging

When developing menus, beginners often encounter problems when elements simply do not appear. The most common mistake is the lack of a theme that supports Action Bar. Make sure that the file AndroidManifest.xml or application styles are using a theme that inherits from Theme.MaterialComponents or Theme.AppCompat. Themes with the prefix NoActionBar hide the standard panel, requiring manual implementation of the Toolbar.

Another common problem is related to paths to resources. An error in the file name (for example, Main_Menu.xml instead of main_menu.xml) or the use of capital letters where this is prohibited will lead to the fact that class generation R will not be successful, and the compiler will complain about the absence of a resource. Always use only lowercase letters, numbers, and underscores when naming resource files.

If icons are not displayed, check their format and presence in the correct folders drawable. Also make sure you don't forget to add the namespace app to the root tag of your menu XML file (xmlns:app="http://schemas.android.com/apk/res-auto"), since without it, attributes like app:showAsAction are simply ignored by the compiler, and elements go into overflow.

Why doesn't my menu appear? on some devices?

This may be due to screen size and settings showAsAction. If set to never, the item will always be hidden in the overflow menu (three dots). If ifRoomand there is not enough space on a narrow screen, it will also hide. Check the layout on emulators with different resolutions.

How to add a separator between menu items?

The standard XML menu does not have a separator tag. However, you can fake it by creating an element with a title consisting of spaces or hyphens and making it non-clickable (android:enabled="false"), or use grouping and styling through custom views, although this requires more code.

Is it possible to change the icon of a menu item at runtime?

Yes, it is possible. In onPrepareOptionsMenu or any other place where you have access to the MenuItem object, call the setIcon(R.drawable.new_icon)method. The changes will be applied instantly the next time the menu is redrawn.

What is the difference between onCreateOptionsMenu and onPrepareOptionsMenu?

onCreateOptionsMenu Called only once when the menu is first created to initialize its structure. onPrepareOptionsMenu Called each time before the menu is shown, which allows you to dynamically change the properties of elements (visibility, text, icons) depending on the current state of the application.

How to hide the standard overflow menu (three dots)?

If all menu items have an attribute showAsAction="always" and fit on the screen, the overflow button will disappear automatically. If you want to hide it forcibly even if there are hidden elements, this requires customizing the theme or using the Toolbar instead of the standard Action Bar with manually setting the OverflowButton.