Custom color in Action Bar + Drawer

A navigation drawer is a common structure for the top-level of our Android app. A drawer provides a safe start point of return with which users can easily understand the application structure.

Using Android Studio, we can create a project from the template of an activity with a navigation drawer:

Create navigation drawer activity

A navigation drawer can be opened by a button placed in the top action bar or by swipe gestures. The default action bar for the drawer contains the icon button that opens/closes it, which is known as the toggle button. The action bar, the title and the button have their own default colors.

Default Action Bar

To change the default action bar with our custom colors, we need to change the styles xml file of our app, which initially only contains the base app theme:

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
 
</style>

Under the style of our custom app theme, we need to add an item for the action bar and an item for the drawer toggle icon (arrow):

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="android:actionBarStyle">@style/MyActionBar</item>
    <item name="drawerArrowStyle">@style/MyDrawerArrowToggle</item>

    <!-- Support library compatibility -->
    <item name="actionBarStyle">@style/MyActionBar</item>
</style>

We also need to add the new colors that we are going to use. These color tags are placed outside the style tag.

<color name="background">#ff82B548</color>
<color name="foreground">@android:color/white</color>

Let’s define each one of these items. Firstly, the custom color for the toggle button:

<style name="MyDrawerArrowToggle" parent="Widget.AppCompat.DrawerArrowToggle">
    <item name="color">@color/foreground</item>
</style>

Secondly, the custom background color of the action bar and also the title text style:

<style name="MyActionBar" parent="@style/Widget.AppCompat.ActionBar">
    <item name="android:titleTextStyle">@style/MyTitleTextStyle</item>
    <item name="android:background">@color/background</item>

    <!-- Support library compatibility -->
    <item name="titleTextStyle">@style/TitleTextStyle</item>
    <item name="background">@color/background</item>
</style>

Finally, the title text style is defined as follows:

<style name="MyTitleTextStyle" parent="@style/TextAppearance.AppCompat.Widget.ActionBar.Title">
    <item name="android:textColor">@color/foreground</item>
</style>

And here it is the result:

Custom Action Bar

Share Button

Leave a Reply

Your email address will not be published.

Time limit is exhausted. Please reload the CAPTCHA.