Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tint menu icons

Tags:

android

xml

menu

I'm building an Android app and I use the icons from the Action Bar Icon Pack to use in the action bar. I define them through the xml files in the menu folder. Is there a way to "tint" these icons so that they are all the same color? So far, I have to do it manually with an image editing software but if I decide to change the color, I have to do it all over again.

I know there is a android:tint attribute for ImageView but I haven't found a way to use it for the menu's icons.

Thanks

like image 853
guillaume-tgl Avatar asked Jun 19 '14 07:06

guillaume-tgl


3 Answers

There may be a better way to do this, but one option is to redraw the icon in code.

Suppose you have a menu item for favorites and want to tint it gray:

MenuItem favoriteItem = menu.findItem(R.id.action_favorite);
Drawable newIcon = (Drawable)favoriteItem.getIcon();
newIcon.mutate().setColorFilter(Color.argb(255, 200, 200, 200), PorterDuff.Mode.SRC_IN);
favoriteItem.setIcon(newIcon);

You can also use a color resource like

newIcon.mutate().setColorFilter(getResources().getColor(R.color.myCustomTint), PorterDuff.Mode.SRC_IN);
like image 174
jimejim Avatar answered Nov 11 '22 03:11

jimejim


If original source of icon is raster image then it's possible to wrap it by <bitmap>.

Add this file into drawable folder - settings_icon.xml:

<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
    android:src="@drawable/ic_action_settings"
    android:tint="@color/colorRed"/>

and then use this drawable for menu item:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="@+id/new_game"
    android:icon="@drawable/settings_icon"
    android:title="@string/settings"
    app:showAsAction="always"/>
</menu>
like image 41
adray Avatar answered Nov 11 '22 03:11

adray


Now you can use tinting from DrawableCompat rather than color filter:

MenuItem favoriteItem = menu.findItem(R.id.action_favorite);
Drawable favoriteIcon = DrawableCompat.wrap(favoriteItem.getIcon());
ColorStateList colorSelector = ResourcesCompat.getColorStateList(getResources(), R.color.tinted_selector, getTheme());
DrawableCompat.setTintList(favoriteIcon, colorSelector);
favoriteItem.setIcon(favoriteIcon);
like image 7
ernazm Avatar answered Nov 11 '22 04:11

ernazm