Search code examples
androidandroid-menulayout-inflater

Android Menu item font using LayoutInflaterCompat.setFactory


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?


Solution

  • 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