Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android TypefaceSpan NoSuchMethodError for new TypefaceSpan(Typeface)

I am working on applying a custom font on TextView from a library and font file is stored in res/font of the app folder.

I got the typeface by using

int id = context.getResources.getIdentifier("xxx","font",packageName);
Typeface typeface = context.getResources.getFont(id);

Typeface is not null, I have put debug points and verified.

TypefaceSpan span = new TypefaceSpan(typeface);

Now I want to create TypefaceSpan object from this typeface and I am getting below error and application crashes.

java.lang.NoSuchMethodError: No direct method (Landroid/graphics/Typeface;)V in class Landroid/text/style/TypefaceSpan; or its super classes (declaration of 'android.text.style.TypefaceSpan' appears in /system/framework/framework.jar!classes2.dex).

Please help. Thanks in advance.

like image 370
Aag1189 Avatar asked Aug 25 '18 01:08

Aag1189


Video Answer


1 Answers

I have the same issue and this answer works for me

You need to create CustomTypefaceSpan class

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 use it like this

TypeFace face = ResourcesCompat.getFont(context, R.font.font_name); // in case you want to support below API 26.
new CustomTypefaceSpan("", face);
like image 118
Mohamed Avatar answered Nov 09 '22 07:11

Mohamed