0

My app supports few languages even though the language support is not given by that device. For this I am downloading TTF files and dynamically setting the TTF files to all views. It works fine everywhere except options menu. Code is added below.

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    menu.clear();
    Typeface typeface = Utils.getTypefaceForAppLanguage(getContext());
    String title = Utils.getLanguageValue(getString(R.string.action_apply));
    inflater.inflate(R.menu.menu_apply, menu);
    menu.findItem(R.id.action_apply).setTitle(typeface != null ? CommonUtils.getStringWithTypeface(typeface, title) : title);
    super.onCreateOptionsMenu(menu, inflater);
}



 public static SpannableString getStringWithTypeface(Typeface typeface, String str) {
    SpannableString spannableString = new SpannableString(str);
    if (!TextUtils.isEmpty(str)) {
        spannableString.setSpan(new CustomTypefaceSpan("", typeface), 0, spannableString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
    return spannableString;
}




public class CustomTypefaceSpan extends TypefaceSpan{

private Typeface newType;

public CustomTypefaceSpan(String family) {
    super(family);
}

public CustomTypefaceSpan(Parcel src) {
    super(src);
}

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);
}
}
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
andro-girl
  • 7,989
  • 22
  • 71
  • 94
  • have u check this https://stackoverflow.com/questions/21942533/how-to-change-custom-font-of-android-menu-item and this https://stackoverflow.com/questions/30668346/how-to-set-custom-typeface-to-items-in-navigationview and this https://stackoverflow.com/questions/4135699/how-to-set-a-font-for-the-options-menu and this https://stackoverflow.com/questions/35551787/how-to-set-a-typeface-to-menu-items-in-overflow-menu-on-toolbar – AskNilesh May 21 '18 at 10:47
  • @Nilesh Yes I have checked most of the answers available. But unfortunately nothing worked. – andro-girl May 21 '18 at 10:56

0 Answers0