Android Menu item font using LayoutInflaterCompat.setFactory

谁都会走 提交于 2019-12-07 16:36:01

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!