【问题标题】:Can't use font in Android无法在 Android 中使用字体
【发布时间】:2016-06-15 17:18:09
【问题描述】:

我已经阅读了所有关于在 Android 中使用字体的 SO 帖子,但我仍然无法让我的工作。我收到以下异常:

java.lang.RuntimeException: native typeface cannot be made

这是我的代码(这个类和静态方法取自here):

public class SafeTypefaces {

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

    public static Typeface get(Context c) {

        final String assetPath = "fonts/robotobold.ttf";

        synchronized (cache) {
            if (!cache.containsKey(assetPath)) {
                try {
                    AssetManager assetManager = c.getAssets();
                    Typeface t = Typeface.createFromAsset(assetManager, assetPath); //Throws exception on this line!
                    cache.put(assetPath, t);
                } catch (Exception e) {
                    L.p("Could not get typeface '" + assetPath + "' because " + e.getMessage());
                    return null;
                }
            }
            return cache.get(assetPath);
        }
    }
}

字体在assets/fonts文件夹中:

(这仍然是 Eclipse。我知道,我知道)。

我尝试过的事情:

  • 我尝试将字体移动到assets 文件夹的根目录并更新assetPath
  • 我检查了文件夹和文件的权限。
  • 我尝试使用应用程序上下文而不是我得到的活动上下文。
  • 我尝试使用不同的字体文件(一个通过电子邮件发送,另一个从 Internet 下载)。

【问题讨论】:

    标签: android android-typeface


    【解决方案1】:

    当我创建这个问题时,我遇到了解决方案。我在这上面花了几个小时,所以我想它值得保留。

    我的问题是我正在做一个图书馆项目。据此(Android Library assets folder doesn't get copied),库项目中的资产对主项目不可用,这就是找不到字体文件的原因。 (同样,这个项目仍然使用 Eclipse。可能不是使用 Gradle+AS 的情况)。

    解决方案是将字体复制到主项目中,瞧!

    【讨论】:

    • “使用 Gradle+AS 可能不是这种情况”——正确。 Android Studio 或其他基于 Gradle 的 Android 构建中的库模块中的资产包含在最终 APK 中。
    猜你喜欢
    • 2020-11-30
    • 1970-01-01
    • 2018-07-18
    • 1970-01-01
    • 1970-01-01
    • 2019-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多