Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to change default font in Android app

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 ?

like image 327
SimenNash Avatar asked Oct 19 '22 16:10

SimenNash


2 Answers

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.

like image 105
sid_09 Avatar answered Nov 04 '22 20:11

sid_09


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.

like image 27
meynety Avatar answered Nov 04 '22 20:11

meynety