Want to learn about the actionbar in Android? We know you do which is why we've put together this tech tutorial which answers all your burning questions. What is an ActionBar? What are the key components? And the age-old questions of why is it even needed? With side by side in-depth explanations in both Java and Kotlin, keep reading to find out how you can use this is your next project.
Let's start with the basics. Action is the response of an Application to any interaction. A user interacts with the App and it behaves in a certain way. The way it acts is known as an Action. An app contains multiple screens which require multiple activities. An activity is an XML file that handles the layout. When an action is performed, it calls the particular layout. This calling requires an action.
Actions are shortcuts to your app. They are objects that can request actions from different components of an app. They can also launch different features of your app in response to a certain interaction. You can add them in your app and call an activity or sub-activity just by pressing a button, switch, or menu item. This may seem complicated but you probably do it daily when using your own phone or tablet.
ActionBar is a menu bar that runs across the top of the activity screen. It is one of the most important UI/UX features of any android action as it provides a visual structure and interactive elements that are familiar to users. It is commonly known as App bar, which makes your app consistent and allows the user to quickly understand the app structure.
Every application has an ActionBar by default. It now has just the title for the current activity as default. An app bar may contain optional menu items which become visible when the user clicks the “menu” action button.
The key functions of the app bar are given below:
In general, an ActionBar consists of the following four components:
Although the ActionBar is quite a useful feature in the Android application, it has some drawbacks as well. We like to keep you informed so we'll list them below, however they're not very significant ones:
Manifest.xml
The ActionBar title at the top of the screen is managed by the AndroidManifest.xml file. In the <activity> tag of your activity, the android:label attribute can be changed to your custom title text.
<application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme"> <activity android:name="com.codepath.example.simpleapp.FirstActivity" android:label="@string/custom_string" > </activity> </application>
Here the custom_string is declared in strings.xml file which is set to the text of your choice.
Activity File
In your activity file, you can also call getSupportActionBar() to retrieve a reference to the ActionBar and modify or access any properties of the ActionBar at runtime as:
Kotlin Code:
supportActionBar.setTitle("My new title") // set the top title val title = actionBar.getTitle().toString() // get the title actionBar.hide() // or even hide the actionbar
Java Code:
ActionBar actionBar = getSupportActionBar(); // or getActionBar(); getSupportActionBar().setTitle("My new title"); // set the top title String title = actionBar.getTitle().toString(); // get the title actionBar.hide(); // or even hide the actionbar
From Android 5.0, material design guidelines discourage the use of the icon in the ActionBar. Although the icon can be added back with the following code:
Kotlin Code:
supportActionBar.setDisplayShowHomeEnabled(true); supportActionBar.setLogo(R.mipmap.ic_launcher); supportActionBar.setDisplayUseLogoEnabled(true);
Java Code:
getSupportActionBar().setDisplayShowHomeEnabled(true); getSupportActionBar().setLogo(R.mipmap.ic_launcher); getSupportActionBar().setDisplayUseLogoEnabled(true);
To set an ActionBar in Android, you have to create a menu XML resource file in menu folder of res folder. You can add toolbar icons and overflow action items into the actionbar. The additional menu items can be declared in raw XML resource file like this:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto"
xmlns:tools="https://schemas.android.com/tools" tools:context=".MainActivity">
<item
android:id="@+id/add"
android:icon="@drawable/ic_menu_add"
app:showAsAction="always"
android:title="@string/add" />
<item
android:id="@+id/reset"
android:icon="@drawable/ic_menu_revert"
app:showAsAction="always|withText"
android:title="@string/reset" />
<item
android:id="@+id/about"
android:icon="@drawable/ic_dialog_info"
app:showAsAction="never"
android:title="@string/about" />
<item
android:id="@+id/exit"
android:icon="@drawable/ic_dialog_info"
app:showAsAction="never"
android:title="@string/exit" />
</menu>
Each menu consists of a menu tag at the root node, and a series of item tags each specifying a Menu Item. The android:title is what is displayed to the user. Each Menu hierarchy must be created as a separate file. Four key attributes that need to be configured for every menu item are:
- always: keeps it in the Action Bar at all times
- ifRoom: keeps it only if space is available
- never: menu item will not be placed in the Action Bar as an icon. It will only be visible when the menu button is clicked, in the popup
- withText:s append to either always or ifRoom, to indicate that the toolbar button to be both the icon and the title, not just the icon
Note: There's no guarantee there'll be a toolbar button. If you ask for 100 always items, you will not have room for all of them. Displaying Menu Items as actions on the app bar should be reserved for those that are very frequently used, critically important for users to discover, or highly expected based on actions available in similar applications. Generic and seldom-used Menu Items, such as settings, help, or about, should never be presented as action items.
To associate a Menu with an Activity, you must first inflate your Menu XML resource into a Menu instance by overriding the Activity’s onCreateOptionsMenu handler. You must return true to display your Menu (false hides the Menu entirely).
Kotlin Code:
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
// You should always call super.onCreateOptionsMenu()
super.onCreateOptionsMenu(menu)
val inflater = menuInflater
inflater.inflate(R.menu.my_menu, menu)
return true
}
Java Code:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// You should always call super.onCreateOptionsMenu()
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.my_menu, menu);
return true;
}
As with layouts, it’s also possible to programmatically create Menu Items, and add them to the Menu object using its add method. The ID used when creating these dynamic Menu Items must always be greater than or equal to the Menu.FIRST constant, to avoid conflicting with any previously inflated Menu Items.
Menus can also be associated with Fragments. Fragment Menus will only be visible on the app bar when the host Fragment is visible. This allows you to dynamically change the actions available to match the content being displayed.
Fragment Menus should be inflated within the Fragment’s onCreateOptionsMenu handler; however, unlike Activities, you must also call setHasOptionsMenu(true) within the Fragment’s onCreate handler.
Kotlin Code:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater) {
inflater.inflate(R.menu.my_menu, menu)
}
Java Code:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.my_menu, menu);
}
By overriding your Activity’s or Fragment’s onPrepareOptionsMenu method, you can modify a Menu based on an application’s current state at run time, immediately before the Menu is displayed. This lets you dynamically disable/enable Menu Items, set visibility, and even modify text.
To modify Menu Items dynamically, you can either record a reference to them from within the onCreateOptionsMenu method when they’re created, or you can use the findItem method on the Menu object.
Kotlin Code:
override fun onPrepareOptionsMenu(menu: Menu): Boolean {
super.onPrepareOptionsMenu(menu)
val menuItem: MenuItem = menu.findItem(R.id.action_filter)
// Modify Menu Items
menuItem.isVisible = false
return true
}
Java Code:
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
MenuItem menuItem = menu.findItem(R.id.action_filter);
// Modify Menu Items
menuItem.setVisible(false);
return true;
}
Android handles the app bar actions and overflow Menu using a single event handler, onOptionsItemSelected. The Menu Item selected is passed into this method as the MenuItem parameter.
To react to the menu selection, compare the item.getItemId value to the resource identifiers in your Menu XML (or the Menu Item identifiers you used when populating the Menu programmatically), and perform the corresponding action.
Kotlin Code:
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Find which Menu Item has been selected
return when (item.itemId) {
R.id.action_favorite -> true
R.id.action_settings -> true
else -> super.onOptionsItemSelected(item)
}
}
Java Code:
public boolean onOptionsItemSelected(MenuItem item) {
// Find which Menu Item has been selected
switch (item.getItemId()) {
// Check for each known Menu Item
case (R.id. action_favorite):
[ ... Perform menu handler actions ... ]
return true;
case (R.id.action_settings):
[ ... Perform menu handler actions ... ]
return true;
//Declare as many cases as required for the menu
// Pass on any unhandled Menu Items to super.onOptionsItemSelected
// This is required to ensure that the up button and Fragment Menu Items
// are dispatched properly.
default: return super.onOptionsItemSelected(item);
}
}
If you have supplied Menu Items from within a Fragment, you can choose to handle them within the onOptionsItemSelected handler of either the Activity or the Fragment. Note that the Activity will receive the selected Menu Item first and that the Fragment will not receive it if the Activity handles it and returns true.
When the user selects one of the app bar items, the system calls your activity's onOptionsItemSelected() callback method and passes a MenuItem object to indicate which item was clicked. In your implementation of onOptionsItemSelected(), call the MenuItem.getItemId() method to determine which item was pressed. The ID returned matches the value you declared in the corresponding <item> element's android: id attribute.
Kotlin Code:
override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) {
R.id.action_settings -> {
// User chose the "Settings" item, show the app settings UI...
true
}
R.id.action_favorite -> {
// User chose the "Favorite" action, mark the current item
// as a favorite...
true
}
else -> {
// If we got here, the user's action was not recognized.
// Invoke the superclass to handle it.
super.onOptionsItemSelected(item)
}
}
Java Code:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
// User chose the "Settings" item, show the app settings UI...
return true;
case R.id.action_favorite:
// User chose the "Favorite" action, mark the current item
// as a favorite...
return true;
default:
// If we got here, the user's action was not recognized.
// Invoke the superclass to handle it.
return super.onOptionsItemSelected(item);
}
}
Let’s have a recap of what we have learned so far: we started with the actions in Android and one of them is the ActionBar. ActionBar is a consistent navigation element that is standard throughout modern Android applications. The ActionBar can consist of: an application icon, an "upward" navigation to logical parent, an application or activity-specific title, primary action icons, and consistent navigation (including navigation drawer). Then we had a brief overview of the advantages, disadvantages, and key components of Actionbar.
We've also gone through the detailed implementation of App Bar in Java as well as Kotlin. You should now know about changing the title, displaying custom icons, managing the layout and menu items in the ActionBar.
Like what you've read or want more like this? Let us know! Email us here or DM us: Twitter, LinkedIn, Facebook, we'd love to hear from you.