2

I want to show the "x" button instead of the default back arrow as the "home" button on toolbar. I have searched how to use a custom image and it works and I have searched how to use a specific color for the back arrow and it works. The problem is, when I put both the custom image and the custom color, it shows the image with its default color, black, when I want it to be blue.

This is the xml for the toolbar:

<android.support.v7.widget.Toolbar
 android:layout_width="match_parent"
 android:layout_height="?attr/actionBarSize"
 android:id="@+id/toolbar"
 android:theme="@style/ThemeToolbar">

And this is the ThemeToolbar style:

<style name="ThemeToolbarDetails" parent="Theme.AppCompat.Light">
    <item name="colorControlNormal">@color/blue</item>
    <item name="homeAsUpIndicator">@drawable/close</item>
</style>

I have tried colorControlNormal, android:textColorSecondary but none of this works when using a custom image.

Andrei Pascale
  • 232
  • 1
  • 3
  • 16

1 Answers1

5

First of all, keep this line on your style: <item name="homeAsUpIndicator">@drawable/close</item>.

Then, you have a couple of ways of solving the color part.

Option 1: If you're working with Vector Drawables, it's easier to just change the color inside the XML file.

Option 2: Alternatively, you can also programmatically tint any menu item. Get the Menu object in the onCreateOptionsMenu() method, and then try the snippet below:

private void tintIcon(@NonNull MenuItem item, int color) {
    Drawable drawable = item.getIcon();

    if (drawable != null) {
        final Drawable wrapped = DrawableCompat.wrap(drawable);
        drawable.mutate();
        DrawableCompat.setTint(wrapped, color);
        item.setIcon(drawable);
    }
}

Option 3: Change the drawable and the color programatically.

final Drawable myIcon =  ContextCompat.getDrawable(context, R.drawable.your_icon);
myIcon.setColorFilter(ContextCompat.getColor(context, R.color.your_color), PorterDuff.Mode.SRC_ATOP);
getSupportActionBar().setHomeAsUpIndicator(myIcon);
Mauker
  • 11,237
  • 7
  • 58
  • 76
  • Thank you! These methods work, I just thought that there was an attribute to replace this code. – Andrei Pascale Aug 17 '18 at 12:40
  • You are welcome! And AFAIK that attribute only works on the original icon for some reason, I never really found a way of making that work through styles. (There might be a way tho, I'm just unaware of it) – Mauker Aug 17 '18 at 12:43
  • One more question, for the other buttons of the action bar, is there an attribute to change their color? – Andrei Pascale Aug 17 '18 at 13:50
  • Try this: https://stackoverflow.com/a/28631979/4070469 (It'll change all the icons tho) – Mauker Aug 17 '18 at 13:52
  • Well then, back to my solution. Programatically tint them. – Mauker Aug 17 '18 at 13:55
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/178210/discussion-between-andrei-p-and-mauker). – Andrei Pascale Aug 17 '18 at 13:56