How to change ActionBar title font when using AppCompat

fragon picture fragon · Jan 3, 2015 · Viewed 9.2k times · Source

I would like to apply custom font to the title of my app which is displayed on the ActionBar. Previously I didn't use any support library and this solution:

int titleId = getResources().getIdentifier("action_bar_title", "id",
                "android");
TextView yourTextView = (TextView) findViewById(titleId);
yourTextView.setTypeface(face);

worked fine for me. But now I am using material design SupportActionBar and this throws NullPointerException. So how to change the ActionBar font when using AppCompat?

Answer

Daniele D. picture Daniele D. · Sep 30, 2015

Assuming you are already successfully using the new toolbar of AppCompat v22+ and that you are importing android.support.v7.widget.Toolbar in your activity.

So on your OnCreate you should already have

toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

at this point you are almost done:

import java.lang.reflect.field;

and add following lines:

TextView yourTextView = null;
try {
    Field f = toolbar.getClass().getDeclaredField("mTitleTextView");
    f.setAccessible(true);
    yourTextView = (TextView) f.get(toolbar);
    yourTextView.setTypeface(face);
} catch (NoSuchFieldException e) {
} catch (IllegalAccessException e) {
}