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
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);
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>
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With