Fontfamily doesn't work on Android Lollipop

1.7k views Asked by At

I want to set sans-serif light as default font in my application. I'm working on Android Lollipop device. So, this is my styles.xml:

<resources>

    <style name="AppBaseTheme" parent="android:Theme.Material.Light.DarkActionBar">

    </style>

    <!-- Application theme. -->
    <style name="AppTheme" parent="AppBaseTheme">
        <!-- All customizations that are NOT specific to a particular API-level can go here. -->
        <item name="android:textViewStyle">@style/RobotoTextViewStyle</item>
        <item name="android:buttonStyle">@style/RobotoButtonStyle</item>


    </style>

    <style name="RobotoTextViewStyle" parent="android:Widget.TextView">
        <item name="android:fontFamily">sans-serif-light</item>
    </style>

    <style name="RobotoButtonStyle" parent="android:Widget.Button">
        <item name="android:fontFamily">sans-serif-light</item>
    </style>

</resources>

When I run the app on my device, the sans-serif-light is not applied in every view. For example, TextViews in ActivityMain.java are showed with the font that I want, but in others activities like SecondActivity.java all the TextViews appear normally. If I run my app on a device with Android 4.1, it works in every view. What am I doing wrong? Thanks in advance :)

1

There are 1 answers

1
Vinay Gaba On

If using the Material Design theme is not important to you, you can use this:

<style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">
<item name="android:typeface">sans-serif-light</item>
</style>

If using the Material Theme is important for your application, you can use the following technique:

import java.lang.reflect.Field;
import android.content.Context;
import android.graphics.Typeface;

public final class FontsOverride {

public static void setDefaultFont(Context context,
        String staticTypefaceFieldName, String fontAssetName) {
    final Typeface regular = Typeface.createFromAsset(context.getAssets(),
            fontAssetName);
    replaceFont(staticTypefaceFieldName, regular);
}

protected static void replaceFont(String staticTypefaceFieldName,
        final Typeface newTypeface) {
    try {
        final Field staticField = Typeface.class
                .getDeclaredField(staticTypefaceFieldName);
        staticField.setAccessible(true);
        staticField.set(null, newTypeface);
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
}
}

Now overload the default fonts in the application class

public final class Application extends android.app.Application {
@Override
public void onCreate() {
    super.onCreate();

    FontsOverride.setDefaultFont(this, "SANS_SERIF", "sans_serif_light.ttf");
}
}