I am trying to change the default font in my app. But its not working. These are steps I have taken:
1) Created class TypefaceUtil.java
import android.content.Context;
import android.graphics.Typeface;
import android.util.Log;
import java.lang.reflect.Field;
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("CustomFontException", "Can not set custom font " + customFontFileNameInAssets + " instead of " + defaultFontNameToOverride);
}
}
}
2) In a class extending Application:
public void onCreate() {
super.onCreate();
TypefaceUtil.overrideFont(getApplicationContext(), "MONOSPACE", "fonts/varelaround_regular.ttf");
}
3) In styles.xml
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="android:typeface">monospace</item>
</style>
Still its not working. Am I missing something ?
I had faced this problem once. I am not very sure why it works, but you can try the following : Instead of "monospace", try each of these: DEFAULT, SANS_SERIF, SERIF. It might not work for all textviews, like those in ListView or recyclerView (weird, right?). But in those cases, I set the typeface programatically from the adapter. Sorry for unable to explain the reason.
For this purpose, i highly recommend you to use Calligraphy
, https://github.com/chrisjenx/Calligraphy, an awesome lib, really strait-forward to change the default font with it, and has many other useful functionalities.
Everything you need to set this up should be in the Readme.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With