Fontfamily doesn't work on Android Lollipop
Asked Answered
C

1

6

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 :)

Campney answered 26/11, 2014 at 19:19 Comment(0)
P
0

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");
}
}
Pylorectomy answered 18/3, 2015 at 13:29 Comment(1)
So, is this a bug in Lollipop?Brashy

© 2022 - 2024 — McMap. All rights reserved.