Pavlo28
Pavlo28

Reputation: 1606

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?

Upvotes: 3

Views: 955

Answers (2)

nosaiba darwish
nosaiba darwish

Reputation: 1247

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

Upvotes: 3

Axay Patel
Axay Patel

Reputation: 47

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.

Upvotes: -1

Related Questions