Options menu in android applications can be customized to set the background or change the text appearance. The background and text color in the menu couldn’t be changed using themes and styles. The android source code (datareslayouticon_menu_item_layout.xml)uses a custom item of class “com.android.internal.view.menu.IconMenuItem”View for the menu layout. We can make changes in the above class to customize the menu. To achieve the same, use LayoutInflater factory class and set the background and text color for the view.
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.my_menu, menu);
getLayoutInflater().setFactory(new Factory() {
@Override
public View onCreateView(String name, Context context,
AttributeSet attrs) {
if (name .equalsIgnoreCase(“com.android.internal.view.menu.IconMenuItemView”)) {
try {
LayoutInflater f = getLayoutInflater();
final View view = f.createView(name, null, attrs);
new Handler().post(new Runnable() {
public void run() {
// set the background drawable
view .setBackgroundResource(R.drawable.my_ac_menu_background);
// set the text color
((TextView) view).setTextColor(Color.WHITE);
}
});
return view;
} catch (InflateException e) {
} catch (ClassNotFoundException e) {
}
}
return null;
}
});
return super.onCreateOptionsMenu(menu);
}
April 28th, 2011 on 4:56 PM
Great post, Thanks for sharing the code for Customizing Background and Text color in Options Menu.
June 29th, 2011 on 5:06 PM
Hi,
Thanks for posting the menu Item concept.
final View view = f.createView(name, null, attrs);
When I declare the view as global instead of local, I able to apply the resource to the last Item of the menu.Not applying to all the menu items.
Is any thing wrong with me?
January 9th, 2012 on 2:24 AM
Didn’t work for me. Always end up with java.lang.IllegalStateException: A factory has already been set on this LayoutInflater
January 30th, 2012 on 3:42 PM
It doesn’t work… Always end with exception…
March 3rd, 2012 on 1:10 PM
doesn’t work
April 4th, 2012 on 9:53 PM
I don’t know why people keep referencing this article, its clearly not working and leaves far to many unanswered questions.
April 28th, 2012 on 8:38 PM
hey, it doesn’t change the inflater menu background , only changes the items background.
May 4th, 2012 on 5:50 PM
instead of LayoutInflater f = getLayoutInflater(); use LayoutInflater li = LayoutInflater.from(context); It will work perfect.