How to change navigation drawer font?

前端 未结 6 2023
别那么骄傲
别那么骄傲 2020-12-13 19:51

I want to use my own font for navigation drawer in android.I use the library comes with android studio according to this answer: https://stackoverflow.com/a/23632492/4393226

6条回答
  •  情书的邮戳
    2020-12-13 20:09

    I found the answer: First create this class in 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) {
            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);
        }
    }
    

    Then add this method to your activity you want to change the font of navigation drawer menu:

    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);
            mi.setTitle(mNewTitle);
    }
    

    and then add call the method you just added in your activity:

    navView = (NavigationView) findViewById(R.id.navView);
    Menu m = navView.getMenu();
    for (int i=0;i0 ) {
            for (int j=0; j 

提交回复
热议问题