我使用的是我在互联网上找到的字体。特别是,当前导致问题的字体是 Amaranth (Google Fonts link) .
我查看了这些问题:
- Native typeface cannot be made
- RuntimeException: native typeface cannot be made
- native typeface cannot be made, exception
- custom font in android studio
所有这些问题似乎都与设备在运行时发生的崩溃有关。我的问题是在尝试使用 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...
}
我已检查并确保以下项目:
- 我的
assets
文件夹位于“app/src/main/assets” - 我的
fonts
文件夹位于“app/src/main/assets/fonts” - 文件名完全“Amaranth-Bold.otf”
运行我的应用程序时,此字体完全符合预期。我已经在 LG Optimus Pro G 和 Droid X 上对此进行了测试。您可以在这些图像中看到结果:
LG Optimus G Pro 屏幕截图
Droid X 屏幕截图
如您所见,字体在两个地方都显示为所需的。您可能也看到,Droid X 屏幕截图显示了一些我需要解决的布局问题。我正在尝试使用 Android Studio 内置的工具在设计时弄清楚如何做到这一点。这只是我要解决的第一个问题。我不想每次都运行应用程序以对布局进行小的调整。尤其如此,因为这是我目前仅有的两个硬件设备,而且我想在更广泛的屏幕尺寸上进行测试(模拟器是 sloooooooooow)。
根据我对其他问题的阅读(主要基于设备在运行时加载字体的事实),我目前的结论是:
- 字体文件没有“损坏”。
- 字体位置没有错。
- 输入的文件名没有错误(扩展名、大小写等)
我还能尝试什么?
最佳答案
我昨天遇到了同样的问题。 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/