James Montemagno
James Montemagno

Live, Love, Bike, and Code.

Tags


Twitter


Fixing activatedBackgroundIndicator in AppCompat Navigation Drawer

James MontemagnoJames Montemagno

I was overly excited when I got news that our amazing component team had finished the latest binding for AppCompat v7 rev 21! This was exciting to me because this meant that any developer could now introduce material design to their Android app and target older devices all the way back to API 7 (although you should just target API 15). I got busy migrating Bike Now over to AppCompat since it used the navigation drawer and seemed like the perfect candidate. The theming changes were pretty simple, however I ran into a big issue with the navigation drawer when using a ListView. The issue is that I was using a TextView to display my menu items and setting the background to:

android:background="?android:attr/activatedBackgroundIndicator"

While this is correct, it leaves my items with different colors on different versions of Android. To top it off, none of them look correct. For instance here is what it looks like on API 19:

This is not great, and on API 21 it will have the apps accent color, which makes no sense at all. What we really want is a nice gray accent like the Google Play Store:

Let’s fix this!

The Drawable State List

The main change is to actually replace the activatedBackgroundIndicator completely with our own drawable. The first thing to do is to specify the color we want to use as our highlight in our colors.xml file:

Then create a new xml in the drawable folder named activatedbackground.xml with the follow state list:

Update Your Theme!

The trick here is that we can completely replace the activatedBackgroundIndicator used throughout our application by overriding it in our base theme with this attribute:



Here is what my full theme looks like:

Update your Item Layout

That should be enough to actually get you up and running, however in Bike Now I actually use an image on the left side of my TextView. If I set the background now to the `activatedBackgroundIndicator` my items will be very upset with me, so I must wrap the `TextView` in a `FrameLayout` with it’s background set to the activatedBackgorundIndicator:

And there you have it, a beautiful state list for your items to match your new material design:

Take a look at my full Bike Now project on GitHub and switch to the lollipop branch to see the code in action.

Live, Love, Bike, and Code

Comments