Júlio Zynger Júlio Zynger - 2 years ago 1116
Android Question

How to set custom typeface to items in NavigationView?

With the new

, we are able to set a drawer's items through a menu resource in XML.

With that, we can set each item with something like

android:title="@string/drawer_my_account" />

But now, I want to set a custom typeface to each of those items in my drawer, and I could not find a way to do that, either by XML or by Java code. Is there a way to do it?

Answer Source

just add following class file to your project.

import android.graphics.Paint;
import android.graphics.Typeface;
import android.text.TextPaint;
import android.text.style.TypefaceSpan;

public class CustomTypefaceSpan extends TypefaceSpan {

    private final Typeface newType;

    public CustomTypefaceSpan(String family, Typeface type) {
        newType = type;

    public void updateDrawState(TextPaint ds) {
        applyCustomTypeFace(ds, newType);

    public void updateMeasureState(TextPaint paint) {
        applyCustomTypeFace(paint, newType);

    private static void applyCustomTypeFace(Paint paint, Typeface tf) {
        int oldStyle;
        Typeface old = paint.getTypeface();
        if (old == null) {
            oldStyle = 0;
        } else {
            oldStyle = old.getStyle();

        int fake = oldStyle & ~tf.getStyle();
        if ((fake & Typeface.BOLD) != 0) {

        if ((fake & Typeface.ITALIC) != 0) {


then create following method to your activity

private void applyFontToMenuItem(MenuItem mi) {
        Typeface font = Typeface.createFromAsset(getAssets(), "ds_digi_b.TTF");
        SpannableString mNewTitle = new SpannableString(mi.getTitle());
        mNewTitle.setSpan(new CustomTypefaceSpan("" , font), 0 , mNewTitle.length(),  Spannable.SPAN_INCLUSIVE_INCLUSIVE);

and call it from activity.

navView = (NavigationView) findViewById(R.id.navView);
        Menu m = navView.getMenu();
        for (int i=0;i<m.size();i++) {
            MenuItem mi = m.getItem(i);

            //for aapplying a font to subMenu ...
            SubMenu subMenu = mi.getSubMenu();
            if (subMenu!=null && subMenu.size() >0 ) {
                for (int j=0; j <subMenu.size();j++) {
                    MenuItem subMenuItem = subMenu.getItem(j);

            //the method we have create in activity

and here is my output

enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download