set app icon to right side in activity tool bar

There is no way android provides to set app icon at right side of actionbar but you can still do that.

Create a menu, say main_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item android:id="@+id/menu_item"
        android:icon="@drawable/your_app_icon"
        android:title="@string/menu_item"
        app:showAsAction="always"/>  //set showAsAction always
                                    //and this should be the only menu item with show as action always

</menu>

Now just override onCreateOptionsMenu in your activity class.

add this in MainActivity.java

@Override
public boolean onCreateOptionsMenu(Menu menu){

    getMenuInflater().inflate(R.menu.main_menu, menu);
    return super.onCreateOptionsMenu(menu);
}

It's done! Your app icon will be visible on right side of ActionBar now.

If you have more than one item in menu then override onPrepareOptionsMenu in activity class and set setEnabled(false) for menu item having app icon, doing this prevents your icon to be clickable.

@Override
public boolean onPrepareOptionsMenu(Menu menu){
    menu.findItem(R.id.menu_item).setEnabled(false);

    return super.onPrepareOptionsMenu(menu);
}

Now your MainActivity.java file would look like

@Override
public boolean onCreateOptionsMenu(Menu menu){

    getMenuInflater().inflate(R.menu.main_menu, menu);
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item){

    switch(item.getItemId()){
        case R.id.menu_item:   //this item has your app icon
            return true;

        case R.id.menu_item2:  //other menu items if you have any
            //add any action here
            return true;

        case ... //do for all other menu items

        default: return super.onOptionsItemSelected(item);
    }
}

@Override
public boolean onPrepareOptionsMenu(Menu menu){
    menu.findItem(R.id.menu_item).setEnabled(false);

    return super.onPrepareOptionsMenu(menu);
}

This is the only trick you can use to set app icon on right side.

Tags:

Android