“无法制作原生字体"只为某些人 [英] "Native typeface cannot be made" only for some people

查看:16
本文介绍了“无法制作原生字体"只为某些人的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序可以更改某些元素的字体.它适用于大多数人,但可能有 0.5% 的人在尝试更改字体时会出现异常.堆栈跟踪的重要部分是这样的:

I have an app that changes the font typeface for some elements. It works well for most of the people, but maybe a 0.5% get an exception when trying to change the font. The significant part of the stack trace is this:

Caused by: java.lang.RuntimeException: native typeface cannot be made
at android.graphics.Typeface.<init>(Typeface.java:147)
at android.graphics.Typeface.createFromAsset(Typeface.java:121)

正如我所说,它适用于大多数人,所以我认为这不是字体文件或我的代码的问题.有关如何解决此问题的任何建议?

As I say, it works for most of the people, so I don't think it is a problem with the font file or my code. Any suggestions about how to solve this?

这是我的代码:

Typeface phoneticFont = Typeface.createFromAsset(getAssets(),
                                                 "fonts/CharisSILR.ttf");
TextView tv;
tv = ((TextView) findViewById(R.id.searchPronunciationTitle));
tv.setTypeface(phoneticFont);

推荐答案

Android OS 的这个 bug 可能是您问题的原因:

This bug of Android OS could be the reason of your issue:

Typeface.createFromAsset 泄露资产流

此错误报告中还有一个解决方法:

Where are also a workaround in this bugreport:

我更改了 HTH 的解决方法,以便该方法不假定字体路径或格式.字体资源的完整路径必须提交为一个参数.我还将对 createFromAsset() 的调用包装在一个try-catch 块,以便 get() 方法将返回 null 如果资产未找到.

I altered HTH's workaround so that the method does not assume the font path or format. The full path of the font asset must be submitted as a parameter. I also wrapped the call to createFromAsset() in a try-catch block so that the get() method will return null if the asset is not found.

public class Typefaces {
    private static final String TAG = "Typefaces";

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

    public static Typeface get(Context c, String assetPath) {
        synchronized (cache) {
            if (!cache.containsKey(assetPath)) {
                try {
                    Typeface t = Typeface.createFromAsset(c.getAssets(),
                            assetPath);
                    cache.put(assetPath, t);
                } catch (Exception e) {
                    Log.e(TAG, "Could not get typeface '" + assetPath
                            + "' because " + e.getMessage());
                    return null;
                }
            }
            return cache.get(assetPath);
        }
    }
}

这篇关于“无法制作原生字体"只为某些人的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆