安卓工作室 : Layout Preview gives "native typeface cannot be made"

标签 android fonts android-studio assets

我使用的是我在互联网上找到的字体。特别是,当前导致问题的字体是 Amaranth (Google Fonts link) .

我查看了这些问题:

所有这些问题似乎都与设备在运行时发生的崩溃有关。我的问题是在尝试使用 Android Studio 的预览工具预览我的布局时出现此异常。

我在“渲染问题”弹出窗口中看到的文本是这样的:

Exception raised during rendering: native typeface cannot be made
java.lang.RuntimeException: native typeface cannot be made   
  at android.graphics.Typeface.<init>(Typeface.java:147)   
  at android.graphics.Typeface.createFromAsset(Typeface.java:121)   
  at app.SegmentButton.onDraw(SegmentButton.java:79)

SegmentButton 中的代码是这样的:

@Override
public void onDraw(Canvas canvas) {

    // Other code...

    String fontPath = "fonts/Amaranth-Bold.otf";
    // The next line is the line that causes the "crash"
    Typeface tf     = Typeface.createFromAsset(mContext.getAssets(), fontPath);
    textPaint.setTypeface(tf);

    // Other code...

}

我已检查并确保以下项目:

  1. 我的 assets 文件夹位于“app/src/main/assets”
  2. 我的 fonts 文件夹位于“app/src/main/assets/fonts”
  3. 文件名完全“Amaranth-Bold.otf”

运行我的应用程序时,此字体完全符合预期。我已经在 LG Optimus Pro G 和 Droid X 上对此进行了测试。您可以在这些图像中看到结果:

LG Optimus G Pro 屏幕截图

enter image description here

Droid X 屏幕截图

enter image description here

如您所见,字体在两个地方都显示为所需的。您可能看到,Droid X 屏幕截图显示了一些我需要解决的布局问题。我正在尝试使用 Android Studio 内置的工具在设计时弄清楚如何做到这一点。这只是我要解决的第一个问题。我不想每次都运行应用程序以对布局进行小的调整。尤其如此,因为这是我目前仅有的两个硬件设备,而且我想在更广泛的屏幕尺寸上进行测试(模拟器是 sloooooooooow)。

根据我对其他问题的阅读(主要基于设备在运行时加载字体的事实),我目前的结论是:

  1. 字体文件没有“损坏”。
  2. 字体位置没有错。
  3. 输入的文件名没有错误(扩展名、大小写等)

我还能尝试什么?

最佳答案

我昨天遇到了同样的问题。 Android Studio 为您提供以下提示:

Use View.isInEditMode() in your custom views to skip code or show sample data when shown in the IDE

像这样重写你的onDraw()方法:

@Override
public void onDraw(Canvas canvas) {            

    // Other code...                   
    if(!isInEditMode())changeFont();
    // Other code...

}

private void changeFont(){
    String fontPath = "fonts/Amaranth-Bold.otf";
    Typeface tf     = Typeface.createFromAsset(mContext.getAssets(), fontPath);
    textPaint.setTypeface(tf);
}

关于安卓工作室 : Layout Preview gives "native typeface cannot be made",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28485365/

相关文章:

android - 如何将 FragmentTabHost 标签放在屏幕底部?

android - 如何将 HSQL(基于文件)与我的 android 应用程序连接?

java - 尊重 Java/Swing 中的字体连字

internationalization - 您如何在网络(和 PDF)上可靠地呈现高棉语(印度语)字体?

java - 从 AsyncTask 中的 SharedPreferences 获取字符串,java.lang.NullPointerException

Java GregorianCalendar 和 Calendar 错位了 2010 年 8 月和 9 月的周末、一个月中的日期

php - 在 Android 应用程序中将数据发布到本地主机

excel - 对象 'Color' 的方法 'Font' 失败

java - 如何为 Javadoc 注释着色

android - 警告 : quick boot/snapshots not supported on this machine