问题
I'm trying to change font of Menu items. According to this answer, I'm using LayoutInflaterCompat.setFactory
(support library 22.1.1 is used in my project). My code looks like this:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_income_mail, menu);
mFilterMenu = menu.getItem(1).getSubMenu();
final LayoutInflater inflaterCopy = getLayoutInflater().cloneInContext(this);
LayoutInflaterCompat.setFactory(inflaterCopy, new LayoutInflaterFactory() {
@Override
public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
// my code
}
});
return true;
}
but method onCreateView(View parent, String name, Context context, AttributeSet attrs)
is never called. What should I change?
回答1:
you have to call the factory onCreateView manually from within your activity onCreateView. because activity's onCreateView returns null by default so if you want other wise you can do like this
@Nullable
@Override
public View onCreateView(String name, Context context, AttributeSet attrs) {
if(name.contains("ActionMenuItemView")) {
LayoutInflater li = LayoutInflater.from(context);
View view = null;
try {
view = li.createView(name, null, attrs);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
if (view != null) {
if(mFactory != null) {
view = mFactory.onCreateView(name,context,attrs);
}
return view;
}
}
return super.onCreateView(name, context, attrs);
}
which will check if LayoutInflater can create the view then trigger the factory onCreateView to edit it
回答2:
are you using fragment?
if you are then you must call following method in "onCreateView"
setHasOptionsMenu(true);
it just acknowledge to system that this fragment has its own option menu.
it worked for me.
来源:https://stackoverflow.com/questions/31319161/android-menu-item-font-using-layoutinflatercompat-setfactory