Search code examples
javaandroidspannablestring

how to avoid SpannableString to span digits


I'm trying to span a String using Spannable String without spanning the digits.

String s = "asd21da";

i want to avoid any changes on the digits and just span the chars. is it possible ?

my code:

@SuppressLint("ParcelCreator")
class TypeFace extends TypefaceSpan {
    Typeface typeface;

    public TypeFace(String family, Typeface typeface) {
        super(family);
        this.typeface = typeface;
    }

    @Override
    public void updateDrawState(TextPaint ds) {
        ds.setTypeface(typeface);
    }

    @Override
    public void updateMeasureState(TextPaint ds) {
        ds.setTypeface(typeface);
    }
}


    public SpannableString spannableString(String s) {
    SpannableString span = new SpannableString(s);
    span.setSpan(new TypeFace("", Typeface.createFromAsset(context.getAssets(),
            "fonts/font.ttf")), 0, span.length(), span.SPAN_EXCLUSIVE_EXCLUSIVE);

    return span;
     }

i use this to change the font of a String but i'm trying to avoid changing digits font.


Solution

  • One way is to set the span to each character if it is not a digit:

    SpannableString span = new SpannableString(s);
    for (int i = 0; i < span.length(); i++) {
        if (Character.isDigit(span.charAt(i)))
             continue;
    
        span.setSpan(new TypeFace("", Typeface.createFromAsset(context.getAssets(),
            "fonts/font.ttf")), i, i+1, span.SPAN_INCLUSIVE_INCLUSIVE);
    }