How to define style that use custom font

2019-09-15 10:30发布

问题:

I would like to use Roboto font as default font for every TextViews, EditTexts, Buttons, etc in my app.

I've put the ttf file in the fonts folder inside assets folder. Now I would like to edit the app style, in order to use that font. So, that's what I've done.

<style name="AppTheme" parent="AppBaseTheme">
    <item name="android:typeface">ROBOTO-REGULAR.TTF</item>
</style>

But the compiler returns this error.

String types not allowed (at 'android:typeface' with value 'ROBOTO-
 REGULAR.TTF').

Is it possible to define via XML a default font for the app? In this case, what is wrong? Thank you in advance.

回答1:

You can't do it the way you want. The android:typeface attribute is an enum and has a fixed number of values. It doesn't take a filename.

What you can do is implement a custom TextView (plus custom Button and EditText inheriting from their respective classes) that reads a custom attribute and loads the font file that the attribute points to.

Bear in mind that Roboto is meant to be used from Honeycomb onwards (or was it ICS?). It does look a bit out of place on older devices, where Droid Sans is the system-wide default.



标签: android fonts