set custom font for text in PreferenceScreen

后端 未结 4 828
独厮守ぢ
独厮守ぢ 2020-12-15 00:08

My PreferenceActivity looks like:

import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.         


        
4条回答
  •  死守一世寂寞
    2020-12-15 00:51

    Maybe more easy to write your own Preference and add it in xml
    just set the custom font via Spannable to the settings fields:
    (looks long but fast done :))

    complete solution:

    private void convertPreferenceToUseCustomFont(Preference somePreference) {
        CustomTypefaceSpan customTypefaceSpan = new CustomTypefaceSpan("", net.mikekober.myMory.utils.Utils.getUsedTypeFace(getActivity()));
    
        SpannableStringBuilder ss;
        if (somePreference.getTitle() != null) {
            ss = new SpannableStringBuilder(somePreference.getTitle().toString());
            ss.setSpan(customTypefaceSpan, 0, ss.length(),Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
            somePreference.setTitle(ss);
        }
    
        if (somePreference.getSummary() != null) {
            ss = new SpannableStringBuilder(somePreference.getSummary().toString());
            ss.setSpan(customTypefaceSpan, 0, ss.length(),Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
            somePreference.setSummary(ss);
        }
    }
    

    call it for every preference and you're done :)

    have fun && good luck

    btw: on changing text, call it again!!
    btw2: checked, seen, applied, improved ;) from: https://stackoverflow.com/a/10741161/371749

    btw3, nearly forgot:

    static private 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);
        }
    }
    

提交回复
热议问题