Skip to content

Instantly share code, notes, and snippets.

@majidnow
Forked from artem-zinnatullin/MyApp.java
Created June 17, 2017 14:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save majidnow/cf10cc558d9885842f92eb9fb331ab62 to your computer and use it in GitHub Desktop.
Save majidnow/cf10cc558d9885842f92eb9fb331ab62 to your computer and use it in GitHub Desktop.
If you need to set one font for all TextViews in android application you can use this solution. It will override ALL TextView's typefaces, includes action bar and other standard components, but EditText's password font won't be overriden.
public class MyApp extends Application {
@Override
public void onCreate() {
TypefaceUtil.overrideFont(getApplicationContext(), "SERIF", "fonts/Roboto-Regular.ttf"); // font from assets: "assets/fonts/Roboto-Regular.ttf
}
}
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="MyAppTheme" parent="@android:style/Theme.Holo.Light">
<!-- you should set typeface which you want to override with TypefaceUtil -->
<item name="android:typeface">serif</item>
</style>
</resources>
import android.content.Context;
import android.graphics.Typeface;
import android.util.Log;
import java.lang.reflect.Field;
public class TypefaceUtil {
/**
* Using reflection to override default typeface
* NOTICE: DO NOT FORGET TO SET TYPEFACE FOR APP THEME AS DEFAULT TYPEFACE WHICH WILL BE OVERRIDDEN
* @param context to work with assets
* @param defaultFontNameToOverride for example "monospace"
* @param customFontFileNameInAssets file name of the font from assets
*/
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("Can not set custom font " + customFontFileNameInAssets + " instead of " + defaultFontNameToOverride);
}
}
}
@majidnow
Copy link
Author

Nice job

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment