So I wanted to make a custom font for my buttons and textviews in my app based on this answer. I know it's doable with this much simpler way, if I just put this in the activity onCreate:
String fontPath = "fonts/Geometos.ttf";
Button mButton = (Button) findViewById(R.id.login_button);
Typeface tf = Typeface.createFromAsset(getAssets(), fontPath);
mButton.setTypeface(tf);
but it's not a nice solution if I want to use custom fonts for many views.
I created the CustomFontHelper, FontCache and MyButton classes just like in the linked answer. I have the same attrs.xml, my style.xml looks like this:
<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>
and here is the view declaration in my activity 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"/>
And of course I have the ttf file in place, since it works well with the simpler solution I copied at the start. I watched what's happening in debug and in the FontCache class this is what happening:
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;
}
meaning in CustomFontHelper class the setTypeFace never gets called. So my question is what's wrong with the createFromAsset call in FontCache? Why does it return null?
EDIT: I also tried skipping FontCache and have this line in CustomFontHelper:
Typeface tf = Typeface.createFromAsset(context.getAssets(), font);
but this causes a runtime faliure with the same reason: "java.lang.RuntimeException: Font asset not found fonts/Geometos.TTF" (My directory for the font is src/main/assets/fonts/Geometos.TTF
EDIT 2: THE PROBLEM WAS .TTF (with capital letters), so if I use <item name="uzoltan.readout:font">fonts/Geometos.ttf</item>
in styles.xml than everything works fine.