[英]Android TypefaceSpan NoSuchMethodError for new TypefaceSpan(Typeface)
我正在从库中对TextView
应用自定义字体,字体文件存储在应用程序文件夹的 res/font 中。
我通过使用得到了字体
int id = context.getResources.getIdentifier("xxx","font",packageName);
Typeface typeface = context.getResources.getFont(id);
字体不为空,我已经把调试点和验证。
TypefaceSpan span = new TypefaceSpan(typeface);
现在我想从这个字体创建 TypefaceSpan 对象,但出现以下错误和应用程序崩溃。
java.lang.NoSuchMethodError: 类 Landroid/text/style/TypefaceSpan 中没有直接方法 (Landroid/graphics/Typeface;)V; 或其超类('android.text.style.TypefaceSpan' 的声明出现在 /system/framework/framework.jar.classes2.dex 中)。
请帮忙。 提前致谢。
我有同样的问题,这个答案对我有用
您需要创建CustomTypefaceSpan
类
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);
}
}
然后像这样使用它
TypeFace face = ResourcesCompat.getFont(context, R.font.font_name); // in case you want to support below API 26.
new CustomTypefaceSpan("", face);
试图重现你的代码,我得到了这些错误:
对于getFont()
调用需要 API 级别 26
对于TypefaceSpan span = new TypefaceSpan(typeface);
调用需要 API 级别 27
你必须至少有这些在 gradle 中:
compileSdkVersion 27
implementation 'com.android.support:appcompat-v7:27.1.1'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.