Developing a mobile application interface is not only a matter of visual appeal, but also of functional ergonomics. In the ecosystem, the app's top bar, known as Android Historically, the top bar of an application, known as ActionBarhas historically played a key role in navigation and access to core features. Users are accustomed to looking here for buttons for searching, setting, adding new elements, or switching modes. However, the standard project template does not always contain the controls you need, and the developer must implement them manually.

Adding an interactive button to this area requires understanding the Android menu architecture, working with XML resources, and handling click events correctly in code. The process may vary depending on whether you are using a native ActionBar or a more modern AppCompatActivity c library. In this article we will analyze all the nuances of implementation, from creating an icon to processing a click, so that your interface becomes intuitive. Toolbar. In this article we will analyze all the nuances of implementation, from creating an icon to processing a click, so that your interface becomes intuitive.

Do not forget that with the release of new versions Android SDK approaches to design change. What worked five years ago may look archaic today or cause warnings in the development environment Android Studio. We will focus on current methods that guarantee correct display on most modern devices.

Preparing resources and creating an icon

The first step before implementing any control is to prepare graphic resources. A button in the action bar cannot exist without a visual image, be it a vector graphic or a raster image. The modern standard recommends using vector drawable resources, as they scale without loss of quality and take up less space in the final APKfile.

Place icon files in a folder res/drawable. If you are using older raster images, be sure to prepare versions for different screen densities (mdpi, hdpi, xhdpi, etc.), although for interface icons this becomes less critical when using vectors. The file name should be concise and understandable, for example ic_action_add.xml or ic_settings.png.

It is important to follow guidelines Material Design regarding the size and indentation of the icon. The standard size of an action icon is 24x24 dp, and the graphics themselves must fit into this square, taking into account the internal padding, so that when clicked, the touch area is sufficient for the user's finger.

โš ๏ธ Attention: Never use images with a transparent background that extends beyond the visible area of โ€‹โ€‹the icon, without taking into account system padding. This may result in the button being visually misaligned or the clickable area not aligning with the graphics.

๐Ÿ’ก

Use the built-in Asset Studio tool in Android Studio (right-click on the drawable folder โ†’ New โ†’ Image Asset) to automatically generate icons in the desired formats and densities.

Customizing the menu file XML

The logical structure of the action bar is defined in a special menu XML file. This is the central configuration element where you declare which buttons will be available to the user. The file is usually located in a directory res/menu and has an extension .xml. Creating this file is a mandatory step, since this is where the identifiers, headers and display priorities of elements are set.

Inside the root tag <menu> elements are created <item>. Each such element corresponds to one button or drop-down list item. The key attribute here is app:showAsAction, which dictates the behavior of the system exactly how to display the button. You can force the button to always be visible, hide it in the overflow menu (three dots), or let the system decide this automatically depending on the available screen space.

You also need to set a unique ID for each element so that you can later identify the click in Java or Kotlin code. It would be a good idea to specify a property android:titlethat will be used as a tooltip on a long press or in the overflow menu for users with accessibility features enabled.

An example file structure might look like this:

<menu xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:app="http://schemas.android.com/apk/res-auto">

<item

android:id="@+id/action_search"

android:icon="@drawable/ic_search"

android:title="Search"

app:showAsAction="ifRoom" />

<item

android:id="@+id/action_settings"

android:icon="@drawable/ic_settings"

android:title="Settings"

app:showAsAction="never" />

</menu>

โ˜‘๏ธ Checking the menu file

Done: 0 / 4

Integrating the menu into the Activity

After the menu resource has been created, it needs to be โ€œconnectedโ€ to your activity. In the life cycle Activity the method onCreateOptionsMenuis responsible for this. By overriding this method, you tell the system which XML file should be used to populate the action bar on the current screen.

Internally, this method uses an object MenuInflaterthat parses the XML and turns its description into actual menu objects. The code should be as concise as possible. Note that the method must return trueto indicate to the system that the menu was successfully created and should be displayed. Return false will cause the panel to remain empty, even if the menu file exists.

If you use AppCompatActivity, make sure you are calling a superclass method or working correctly with the Menuobject passed as an argument. In modern versions of Android, it is also important to consider the theme of the application: if you are using a theme without ActionBar (NoActionBar), you will need to explicitly initialize Toolbar and assign a menu to it separately.

The implementation of the method in Java looks like this:

@Override

public boolean onCreateOptionsMenu(Menu menu) {

getMenuInflater().inflate(R.menu.main_menu, menu);

return true;

}

This code is a standard template for most applications. However, if you need to dynamically change the composition of the menu depending on the state of the application (for example, showing a Delete button only when a list item is selected), the logic can be complicated by pre-inflation condition checks.

What if the menu does not appear?

Check if the application theme is not overridden to Theme.NoActionBar. In this case, the standard ActionBar is hidden, and you need to add a Toolbar widget to the layout and call setSupportActionBar(toolbar).

Handling button clicks

Creating a visual button is only half the battle. For the interface to become functional, it is necessary to implement a response to user actions. In Android, the method onOptionsItemSelectedis responsible for this. It is called by the system every time the user clicks on any item in the action bar or drop-down menu.

Inside this method you receive an object MenuItemthat contains information about what exactly was clicked. The main processing mechanism is the construction switch (or if-else), which checks the ID of the clicked element. For each case, you write the necessary logic: starting a new activity, opening a dialog box, performing a search, or saving data.

It is extremely important to return true after processing the event to inform the system that the click was processed and does not require further transmission. If you return false or call a supermethod on a raw ID, the system may try to handle the click in other ways or simply ignore it.

An example of processing is as follows:

@Override

public boolean onOptionsItemSelected(MenuItem item) {

int id = item.getItemId();

if (id == R.id.action_search) {

// Search logic

openSearchView();

return true;

} else if (id == R.id.action_settings) {

// Go to settings

startActivity(new Intent(this, SettingsActivity.class));

return true;

}

return super.onOptionsItemSelected(item);

}

  • ๐Ÿ” Always check the element ID before performing actions to avoid logic errors.
  • ๐Ÿ›ก๏ธ Use return true only after the event handling code has successfully completed.
  • ๐Ÿ”„ For complex actions, call separate methods to avoid clutter onOptionsItemSelected.

Features of working with Toolbar and Material Design

In modern applications, the classic one ActionBar is often replaced with a more flexible widget Toolbar. This allows you to place the panel anywhere on the screen, make it transparent or change color dynamically. The principle of adding buttons remains similar, but there are important differences in initialization.

When using Toolbar you must explicitly associate it with the activity through the setSupportActionBarmethod. Only after this connection the methods onCreateOptionsMenu and onOptionsItemSelected will begin to work with your toolbar. If you forget this step, the menu will simply not appear, and you will spend a lot of time debugging a non-existent problem.

In addition, Material Design suggests the use of special components, such as SearchViewintegrated directly into the action bar. This requires additional configuration in the XML menu, where the attribute app:actionViewClass points to the widget class. Such a button turns into a full-fledged input field when pressed.

๐Ÿ’ก

Toolbar gives complete freedom of placement, but requires manual binding via setSupportActionBar() to work with the menu.

It is also worth considering the behavior of the buttons when the screen is rotated. If your action bar contains critical data or state, make sure it is preserved when you recreate the activity. The visual display of buttons is restored automatically by the system, but their state (for example, the active filter) must be saved manually.

Attribute table showAsAction

Understanding display attributes is critical to creating a user-friendly interface. The wrong choice can lead to important buttons being hidden in the menu, and unimportant ones taking up all the space on the screen. Below is a table describing the main values of the attribute app:showAsAction.

Attribute value Description of behavior Recommendation for use
always The button is always displayed in the panel if there is space. Use only for the most important actions (1-2 buttons).
ifRoom The button is shown in the panel if there is free space. The optimal choice for most secondary actions.
never The button is always hidden in the overflow menu (three dots). For rarely used functions (Settings, About the application).
withText Show the button title along with the icon. Rarely used, only if the icon is not clear without a caption.

Combining these flags through the pipe character (for example, ifRoom|withText) allows you to fine-tune the behavior. However, it is worth remembering that the space on the screen of a mobile device is limited, and abuse of the flag always leads to displacement of the activity title and deterioration of the readability of the interface.

๐Ÿ“Š What type of buttons do you most often add to the ActionBar?
Icons only
Icons with text
Text only
Complex widgets (SearchView)

Frequent errors and debugging

Even experienced developers encounter problems when working with menus. One of the most common mistakes is missing a namespace xmlns:app in the root tag of the menu file. Without this attribute, the system will not recognize commands showAsActionand all buttons will default to the overflow menu, ignoring your settings.

Another common problem is related to the theme of the application. If you are using a theme that inherits from Theme.AppCompat.Light.NoActionBarbut did not add Toolbar to the layout, the action bar simply will not appear. There may be no obvious errors in the logs, which confuses beginners. Always check the widget hierarchy in the Layout Inspector.

โš ๏ธ Attention: If you have changed the menu file, but the changes are not displayed on the emulator or device, perform a complete rebuild of the project (Build โ†’ Rebuild Project). Android Studio's resource cache sometimes prevents menu XML files from instantly updating.

You should also pay attention to the colors of the icons. On a light background, the dark icon is clearly visible, but if the application theme is dark, the black icon will blend into the background. Use an attribute android:tint or vector drawables with dark theme support to ensure interface contrast in any lighting conditions.

When debugging click logic, it is useful to display messages in Logcat. This will ensure that the method onOptionsItemSelected is called at all. If there are no calls, the problem almost certainly lies in the initialization stage of the menu or Toolbar binding.

Why does the icon not change after replacing the file in the drawable?

Android caches resources. Try changing the icon file name and updating the link in the XML menu, or clearing the IDE cache via File โ†’ Invalidate Caches / Restart.

FAQ: Frequently Asked Questions

How to add more than two buttons to the visible part of the ActionBar?

The Android system automatically hides buttons in the menu overflow if they don't fit. Forcing more than 2-3 buttons with icons to be displayed is not recommended from a UX point of view, as it clutters the interface. If this is critically necessary, you can use the flag always for all buttons, but on narrow screens they may be cut off.

Is it possible to change the color of a button icon programmatically?

Yes, it is possible. You can get an object MenuItem in a method onCreateOptionsMenu, call getItemIcon(), apply to it setColorFilter() and set it back via setIcon(). This is useful for indicating the active state of the button.

Why is the onOptionsItemSelected method not called?

Most often this happens if you accidentally intercepted the event in another place (for example, in the click handler of the Toolbar itself) and returned true, or if the menu was not created correctly inflated in onCreateOptionsMenu. Also check if the method in the parent class is not overridden incorrectly.

How to hide a button at a certain point in the application?

To do this, you need to get a link to the menu (saving the object Menu during creation) and call the method findItem(R.id.your_id).setVisible(false). To show the back button, use setVisible(true). Changes will be applied instantly.