MarshallLee
MarshallLee

Reputation: 1330

Android: How to change the colour of menu icons

How can I change the colour of the menu icon on the action bar programmatically, not using styles.xml?

I found a really simple solution, to use the setTint() method, but this only seems to apply for the Lollipop and above.

Upvotes: 1

Views: 77

Answers (2)

Jared Rummler
Jared Rummler

Reputation: 38121

On phone, will improve later. This should work:

MenuItem menuItem = menu.findItem(R.id.your_menu_item);
Drawable drawable = menuItem.getIcon();
if (drawable != null) {
    // If we don't mutate the drawable, then all drawable's with this id will have a color
    // filter applied to it.
    drawable.mutate();
    drawable.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
    drawable.setAlpha(alpha);
}

Upvotes: 1

RussHWolf
RussHWolf

Reputation: 3644

You can tint in a backwards-compatible way using DrawableCompat in the support library. The API requires a bit of wrapper boilerplate to work.

MenuItem item = ... // The menu item you want to change color
Drawable icon = item.getIcon();
int tintColor = ... // The color you want, expressed as a color value, not an int resource.
Drawable tintWrapper = DrawableCompat.wrap(icon);
DrawableCompat.setTint(tintWrapper, tintColor);
item.setIcon(tintWrapper);

Upvotes: 0

Related Questions