【发布时间】:2015-12-29 13:08:44
【问题描述】:
所以我想根据this 答案为我的应用程序中的按钮和文本视图制作自定义字体。我知道用这种更简单的方法是可行的,如果我把它放在活动 onCreate 中:
String fontPath = "fonts/Geometos.ttf";
Button mButton = (Button) findViewById(R.id.login_button);
Typeface tf = Typeface.createFromAsset(getAssets(), fontPath);
mButton.setTypeface(tf);
但如果我想为许多视图使用自定义字体,这不是一个好的解决方案。
我创建了 CustomFontHelper、FontCache 和 MyButton 类,就像在链接的答案中一样。我有相同的 attrs.xml,我的 style.xml 看起来像这样:
<style name="Button" parent="@android:style/Widget.Button">
<item name="android:background">@color/colorPrimary</item>
<item name="android:textSize">50sp</item>
<item name="android:textColor">@color/SecondaryTextColor</item>
<item name="uzoltan.readout:font">fonts/Geometos.TTF</item>
</style>
这是我的活动 xml 中的视图声明:
<uzoltan.readout.Font.MyButton //my package name is uzoltan.readout and I have the MyButton, FontCache and CustomFontHelper classes in a package called Font
style="@style/Button"
android:id="@+id/login_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:text="@string/login_button_text"/>
当然,我有 ttf 文件,因为它与我一开始复制的更简单的解决方案配合得很好。我观察了调试和 FontCache 类中发生的情况:
Typeface tf = fontCache.get(name); //returns null
if(tf == null) {
try {
tf = Typeface.createFromAsset(context.getAssets(), name); //still returns null
}
catch (Exception e) { //Runtime exception, font asset not found fonts/Gemetos.TTF
return null;
}
在 CustomFontHelper 类中意味着永远不会调用 setTypeFace。所以我的问题是 FontCache 中的 createFromAsset 调用有什么问题?为什么返回null?
编辑:我也尝试跳过 FontCache 并在 CustomFontHelper 中有这一行:
Typeface tf = Typeface.createFromAsset(context.getAssets(), font);
但这会导致运行时失败,原因相同:“java.lang.RuntimeException: Font asset not found fonts/Geometos.TTF” (我的字体目录是 src/main/assets/fonts/Geometos.TTF
编辑 2: 问题是 .TTF(大写字母),所以如果我使用 <item name="uzoltan.readout:font">fonts/Geometos.ttf</item>
in styles.xml,那么一切正常。
【问题讨论】:
-
检查@jinosh 答案
标签: android android-view android-fonts android-typeface