With the new Palette library and Material design, we’re able to create more color-aware applications, implementing color adaptable user interfaces.

TL;DR There’s a link to the ColorizeToolbarHelper class at the end of the article. It works out of the box.

Instead of using the same colors across the app, we’re can easily colorize the views, using leading colors of on screen visible pictures. Here are examples of few views already colorized according to the leading image palette.

material_toolbar

Todays article is focused on dynamic colorizing of Toolbar views (icons and textviews), so they fit the color scheme choosen by palette algorithms (Please follow this link to find out how to use Palette library). As achieving this with use of Themes may turn impossible, we took different approach, where each toolbars child-view is colorized with ColorFilter. It’s achieved in 4 steps:

  1. Changing the color of back button (or open drawer button).
  2. Changing the color of any ActionMenuViews – icons that are not back button, nor text, nor overflow menu icon.
  3. Changing the color of title and subtitle.
  4. Changing the color of the Overflow Menu icon.

The following code is based on Compatibility libraries (Appcompat, and Palette) so it will work not only on Lollipop, but on all Android devices (as regular Appcompat based apps).

Let’s color it up!

To get all Toolbar views, we iterate through all it’s child views and colorize them separately. The loop code for it looks like this:

  

The above code is pretty self explanatory, however to have it working, we need extra steps to colorize the overflow menu icon.

The Overflow Menu Icon

The following solution is taken from the StackOverflow thread : http://stackoverflow.com/questions/22046903/changing-the-android-overflow-menu-icon-programmatically/22106474#22106474 We reprint it here to have the whole working toolbar colorization feature at hand.

First we need to add the content description attribute to the overflow menu icon in styles.xml file. It can be any string, it’s just needed to find the proper view later in code by it’s description.

  

Second, we implement the method responsible for finding and colorizing the Overflow Icon:

  

Third, we remove the global layout listeners, as they’re no longer needed.

  

And voilà, the Toolbar icons have they’re unique new colors! :)

Toolbar background color

Just for the reference, to change the background color of a toolbar, we simply use the setBackgroundColor method on the reference to Toolbar object:

  

Full source code

Here’s a helper class that does all the job for you : ToolbarColorizeHelper on Gist Just call in the fragments onResume method:

  

In the next episode, we will show you how to create header parallax effects. Stay tuned for more!