Search code examples
javaandroidxmlandroid-actionbaraction

Settings button with icon in Action Bar


As title says i don't know how to add button to android action bar near title of app with icon.

I need to add it here as shown on picture enter image description here


Solution

  • First, create a menu resource, name it whatever you want.

    Then, add this to your new .xml resource:

    <menu xmlns:tools="http://schemas.android.com/tools"
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        tools:ignore="AlwaysShowAction">
        <item android:id="@+id/your_item_id"
            android:icon="@drawable/your_drawable_id"
            android:title="@string/your_string_id"
            app:showAsAction="always" />
    </menu>
    

    The item tag defines the id, the icon and the title. the showAsAction defines if item is located at the action bar or submenu.

    It's recommended to use string resources for your title, specially if you want to translate your app.

    The menu icon is defined by your drawable resource. In order to use the correct size, I recommend to use the default icon asset wizard.

    Add this to your Activity to add the menu:

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

    In order to detect menu pushes, use this:

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.your_item_id) {
            //Do your stuff here
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    

    More info: https://developer.android.com/guide/topics/ui/menus.html