Adding Action Buttons In Toolbar

Now we need to add some action buttons in Toolbar, Let’s open menu_main.xml located under res ⇒ menu and add the search menu item as mentioned below.

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="akraj.snow.test.MainActivity">
    <!-- Search -->
    <item
        android:id="@+id/action_search"
        android:icon="@drawable/ic_action_search"
        android:title="@string/action_search"
        app:showAsAction="ifRoom"/>
    <!-- Settings, should always be in the overflow -->
    <item android:id="@+id/action_settings"
        android:title="@string/action_settings"
        app:showAsAction="never"/>
</menu>

The app:showAsAction attribute specifies whether the action should be shown as a button on the app bar.

ifRoom The action is displayed as a button if there is room in the app bar for it; if there is not enough room, excess actions are sent to the overflow menu.
always The action is displayed as a button in the app bar.
never The action is always listed in the overflow menu, not displayed in the app bar.


Tip: You can find some icons on the Google Material Icons page.
Tip: If necessary, you can re-order the menu items with the android:orderInCategory attribute in each <item> you need to move.

Adding Images in Application

To import the Image in Android Studio, right click on res ⇒ New ⇒ Image Asset. It will show you a popup window to import the resource. Browse the search icon that you have downloaded from Google Material Icons page , select Action Bar and Tab Icons for Asset Type and give the resource name as ic_search_action and proceed.

To specify the options menu for an activity, override onCreateOptionsMenu() method. For example:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu_main, menu);
    return true;
}

Handling click events

When the user selects an item from the options menu (including action items in the app bar), the system calls your activity’s onOptionsItemSelected() method. For example:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.action_settings:
            // some code
            return true;
        case R.id.action_search:
            // some codes like toast message
            Toast.makeText(getApplicationContext(), "Congratulations!!!", Toast.LENGTH_SHORT).show();
            return true;
        default:           
            return super.onOptionsItemSelected(item);
    }
}

Now you can run you app for testing action buttons.
Next Lesson : Moving From One Activity To Another Activity

About the author

Akshay Raj

View all posts