gpt4 book ai didi

android - RuntimeException:自定义 TextView 加载字体无法制作原生字体或内存泄漏

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:38:09 27 4
gpt4 key购买 nike

我的代码中存在一个巨大的问题,我正在从自定义 TextView 类中将字体加载到我的 assets\fonts\ 文件夹中。第一个问题是它在 4.0 设备上崩溃并出现异常 Caused by: java.lang.RuntimeException: native typeface cannot be made。我正在使用相同的过程 here使用方法:

public class MyTextView extends TextView {

public MyTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}

public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}

public MyTextView(Context context) {
super(context);
}


public void setTypeface(Typeface tf, int style) {
if (style == Typeface.BOLD) {
super.setTypeface(Typeface.createFromAsset(
getContext().getAssets(), "fonts/hirakakupronbold.ttf"));
} else if (style == Typeface.ITALIC) {
super.setTypeface(Typeface.createFromAsset(
getContext().getAssets(), "fonts/hirakakupronitalic.ttf"));
} else {
super.setTypeface(Typeface.createFromAsset(
getContext().getAssets(), "fonts/hirakakupron.ttf"));
}
}
}

请注意,我正在使用扩展名 .ttf,我发现这是导致 RunTimeException 的原因。所以我用 .otf 扩展名转换了各自的字体,现在它已经在 4.0 设备上运行但是有内存泄漏基于 here .有变通办法here但我不知道如何使用/调用它。任何帮助都可以,谢谢。

最佳答案

好吧,所以我终于想到在 TextView 类中实例化一个 TypeFace 对象会在每次相同的 TextView 时造成如此多的负载实例化。这导致我的应用程序延迟并最终导致 OutOfMemoryException。所以我所做的是创建一个不同的自定义 TypeFace 类,它会从 Assets 中调用我的字体,以便它从 TypeFace 类而不是从 TextView 实例化 类。

这是我的 TypeFaces 类:

public class TypeFaces {

private static final Hashtable<String, Typeface> cache = new Hashtable<String, Typeface>();

public static Typeface getTypeFace(Context context, String assetPath) {
synchronized (cache) {
if (!cache.containsKey(assetPath)) {
try {
Typeface typeFace = Typeface.createFromAsset(
context.getAssets(), assetPath);
cache.put(assetPath, typeFace);
} catch (Exception e) {
Log.e("TypeFaces", "Typeface not loaded.");
return null;
}
}
return cache.get(assetPath);
}
}
}

和自定义 TextView 类:

public class TextViewHirakaku extends TextView {

public TextViewHirakaku(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}

public TextViewHirakaku(Context context, AttributeSet attrs) {
super(context, attrs);
}

public TextViewHirakaku(Context context) {
super(context);
}

public void setTypeface(Typeface tf, int style) {
if (style == Typeface.BOLD) {
super.setTypeface(TypeFaces.getTypeFace(getContext(),
"fonts/hirakakupronbold.ttf"));
} else if (style == Typeface.ITALIC) {
super.setTypeface(TypeFaces.getTypeFace(getContext(),
"fonts/hirakakupronitalic.ttf"));
} else {
super.setTypeface(TypeFaces.getTypeFace(getContext(),
"fonts/hirakakupron.ttf"));
}
}
}

请注意,我现在从此处的 TypeFaces 类调用 getTypeFace 方法。

关于android - RuntimeException:自定义 TextView 加载字体无法制作原生字体或内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20942671/

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