In this article, we will see how to add icons and change background color in the options menu of the toolbar. Option menu is a collection of menu items of an activity. Android Option Menus are the primary menus of the activity. They can be used for settings, search, delete items, etc. We will first create vector assets for the icon. Then we will set the icon in the toolbar items. Similarly, for the background, we will first create a custom style for the toolbar. Then we will set the theme in the toolbar.
Step by Step Implementation
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio.
Step 2: Implement Option Menu
To create option menu of an activity in Android Studio refer to How to implement Options Menu in Android.
Step 3: Add Vector Assets
Right Click on the drawable folder and go to the new vector asset. Search from many vector icons and create one. You can also add an image from the outside but with the right dimension.
Step 4: Define Colors
It is always better to pre-define strings and colors instead of hard coding them hence we will define the colors.
- Open the colors.xml file by navigating to the app -> res -> values -> colors.xml.
- Create a color tag inside the resources tag with a name and set a color with its hex code.
Add the below lines inside the colors.xml file.
Step 5: Create Custom Style
We need to create a new style with parent=”ThemeOverlay.AppCompat.Light” as the parent theme. Below is the code for style.
Step 6: Set Style in Toolbar
In the toolbar tag set the style in the popupTheme attribute. Look at the code below for reference.
Step 7: Add the Icons to the Items
- Go to the menu.xml file where the items are created
- Set the main item tag’s showAsAction attribute to always
- Set the icon in the sub-items tag using the icon attribute