Wednesday, June 22, 2011

How to change the text color of Android options menu

As promised in the previous post, here comes the second installment of styling the options menu.  In the previous post we saw how we could change the background color of the options menu.  This time we are going to look at how we could change the text color of Android options menu.

We already know that styling the options menu is not really easy.  As shown in the previous post, its a eight step process.  To change the text color of the options menu we need to put in another hack.  We need to add a ninth step.  Lets look at all nine steps once again.
  1. Setting the custom LayoutInflater.Factory instance.
  2. Implementing the onCreateView method that will actually set the background selector for the options menu.
  3. In the implementation of onCreateView, check if the view that is to be created is of type com.android.internal.view.menu.IconMenuItemView.  Yes, I know, its an *internal* class!
  4. If the view is of type IconMenuItemView then create the view using the LayoutInflater.
  5. At this point we have an instance of IconMenuItemView but we cannot change the background color of the view directly.  Even if we change the background color at this point, framework updates it again and our changes are overwritten
  6. We have to change the background color after the view has rendered, using the Handler API.
  7. Change the background color in run method of the Runnable instance that we pass to the Handler's post method.
  8. Change the text color using reflection.  This is the new step.  We need to change the text color using reflection.
  9. Catch all exceptions that could occur in the entire process.  Notice that, we are using an internal class there are high changes that its behavior could change without any notice.  In fact this approach does not work on Android 2.3.  In this case we have to fallback to the default menu styling.
Lets look at code to make things clear

The menu_selector.xml and colors.xml have been kept unchanged from the previous post.  The comments are embedded in the code.  One new methods has been added setTextColor.  This method does the job for us!
The above screenshot shows the menu item color changes when its pressed.

That's it!  We have successfully changed the background color and text color of Android options menu.
Have some Fun!