Kaloyan Roussev
Kaloyan Roussev

Reputation: 14711

How to change actionbar menuitem's font?

I have to set the entire application's font, so far Ive done it everywhere but the menuitems that appear at the right-hand side of the actionbar.

Here is how I set create one:

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    MenuItem item = menu.add(21, 66, 0, "Send");
    item.setTitle("Send");
    item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
}

How do I set a certain typeface to this item?

Upvotes: 0

Views: 151

Answers (1)

Sirwan Afifi
Sirwan Afifi

Reputation: 10824

You can use this code:

Typeface typeface = Typeface.createFromAsset(getAssets(),"fonts/font.ttf");
TypefaceSpan actionBarTypeFace = new CustomTypefaceSpan("", typeface);
SpannableString s = new SpannableString("Item");
s.setSpan(actionBarTypeFace, 0, s.length(),
                    Spannable.SPAN_INCLUSIVE_INCLUSIVE);
MenuItem item = menu.add(21, 66, 0, s);
item.setTitle(s);

CustomTypeFaceSpan:

public class CustomTypefaceSpan extends TypefaceSpan {
    private final Typeface newType;

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

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

    @Override
    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) {
            paint.setFakeBoldText(true);
        }

        if ((fake & Typeface.ITALIC) != 0) {
            paint.setTextSkewX(-0.25f);
        }

        paint.setTypeface(tf);
    }
}

Upvotes: 2

Related Questions