gpt4 book ai didi

java - 自定义字体未应用

转载 作者:行者123 更新时间:2023-12-02 03:26:37 24 4
gpt4 key购买 nike

我的自定义字体类

public class CustomFontText extends TextView {
/*
* Caches typefaces based on their file path and name, so that they don't have to be created every time when they are referenced.
*/
private static Typeface mTypeface;

public CustomFontText(final Context context) {
super(context, null);
}

public CustomFontText(final Context context, final AttributeSet attrs) {
super(context, attrs, 0);
readAttrs(context, attrs);
}

public CustomFontText(final Context context, final AttributeSet attrs, final int defStyle) {
super(context, attrs, defStyle);
readAttrs(context, attrs);
}

private void readAttrs(Context context, AttributeSet attrs) {
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomTextView);

// Read the title and set it if any
String fontName = a.getString(R.styleable.CustomTextView_fontname);
if (fontName != null) {
// We have a attribute value
if (mTypeface == null) {
mTypeface = Typeface.createFromAsset(context.getAssets(), fontName);
setTypeface(mTypeface);
}
}

// a.recycle();
}
}

在XMl文件中应用

<somepackage.CustomFontText
android:id="@+id/details"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ewfewfewqfewfwef"
custom:fontname="Roboto-Regular.ttf" />

它没有给出任何类型的错误,但我无法查看 TextView 中的任何更改。更改字体名称没有什么区别。

最佳答案

将代码 setTypeface(mTypeface); 移至 mTypeface == null 检查之外应该可以解决该问题。所以代码应该如下所示:

if (mTypeface == null) {
mTypeface = Typeface.createFromAsset(context.getAssets(), fontName);
}
setTypeface(mTypeface);

这是因为 mTypeface 被声明为 static,并且所有 CustomFontText 实例共享相同的字体(这对于缓存有意义)。如果在检查内部调用 setTypeface,则只会在首次加载字体时应用一次。

关于java - 自定义字体未应用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38784285/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com