Customize icons on the android toolbar

Hey what’s up, so in this article we’ll look on how to customize the icons on the toolbar of your android application. This is useful in various situations where you’d like more control on how your application looks. The results we are trying to achieve are shown below

Customize the icon to get a yellow or white icon on the toolbar

Before we customize

Before we start the customization, you need to have the icons you want to use in the drawable folder. The icons I use in this article are of 24dp, which can be found here.

You should also ensure that there is an actual menu being inflated. If you don’t know how to do this, you can check this example here.

Note: Android studio automatically does this for you when creating your first “MainActivity” using the “Basic Activity” template.

Let’s customize

The first thing we’ll do is to override the “onPrepareOptionsMenu” function, on the activity or fragment you are to customize the toolbar icons.

So, what just happened?

Now, although I’ve made the effort to explain the code by comments, there’s those who will still have trouble getting what exactly is going on.

  1. We created a MenuItem variable to hold the item we want to customize. The ‘R.id.action_refresh‘ is the ID of our menu item.
  2. We then create a Drawable variable to hold the icon we want to assign to the menu item.
  3. We apply a colorFilter to the icon, this is where we assign the custom color we want for the icon. The ‘R.color.toolBarIcon‘ is the name of color value in the color.xml file
  4. We set the customized icon as the icon to be used for the menuItem.

If things are successful, you should now be able to customize the icons to any color you desire.

Doing the same using fragments

When it comes to fragment, the only thing that changes is the return type of the ‘onPrepareOptionsMenu‘ method. When using activities, the method returns a boolean. For fragments, the method returns a void i.e nothing.

Here’s how the same code would look like for a fragment:

Thank you very much for reading this far.

Use the social buttons below to spread the word to fellow developers about what you just learned. (Please, be a nice guy)…