If you need to install one font for all TextViews in an Android application, you can use this solution. It will override all TextView fonts, include an action bar and other standard components, but the EditText password font will not be exceeded.
Myapp.java
public class MyApp extends Application { @Override public void onCreate() { TypefaceUtil.overrideFont(getApplicationContext(), "SERIF", "fonts/Roboto-Regular.ttf"); } }
TypefaceUtil.java
public class TypefaceUtil { public static void overrideFont(Context context, String defaultFontNameToOverride, String customFontFileNameInAssets) { try { final Typeface customFontTypeface = Typeface.createFromAsset(context.getAssets(), customFontFileNameInAssets); final Field defaultFontTypefaceField = Typeface.class.getDeclaredField(defaultFontNameToOverride); defaultFontTypefaceField.setAccessible(true); defaultFontTypefaceField.set(null, customFontTypeface); } catch (Exception e) { Log.e("TypefaceUtil","Can not set custom font " + customFontFileNameInAssets + " instead of " + defaultFontNameToOverride); } }
}
themes.xml
<?xml version="1.0" encoding="utf-8"?> <resources> <style name="MyAppTheme" parent="@android:style/Theme.Holo.Light"> <item name="android:typeface">serif</item> </style> </resources>
Update for Android 5.0 or higher
As I researched and tested on a device running api 5.0 or higher, this solution works fine, because I use a single style.xml file and do not make another style.xml in the values-21 folder
Although, Some users ask me that this solution does not work with Android device version 5.0 (they can use -21 style.xml values, I think)
So, this is due to the fact that in API 21 most text styles include fontFamily setting, e.g.
<item name="fontFamily">@string/font_family_body_1_material</item>
Uses the default Roboto Regular font:
<string name="font_family_body_1_material">sans-serif</string>
So the best solution is
If someone has a problem not working on 5.0+. Do not override the font in your v21 value styles.
Just redefine the font in /style.xml values ββand it will be useful for you :)