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.
- Setting the custom LayoutInflater.Factory instance.
- Implementing the onCreateView method that will actually set the background selector for the options menu.
- 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!
- If the view is of type IconMenuItemView then create the view using the LayoutInflater.
- 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
- We have to change the background color after the view has rendered, using the Handler API.
- Change the background color in run method of the Runnable instance that we pass to the Handler's post method.
- Change the text color using reflection. This is the new step. We need to change the text color using reflection.
- 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.
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!
That's it! We have successfully changed the background color and text color of Android options menu.