Fontfamily not working on Android Lollipop

I want to set sans-serif light as the default font in my application. I am working on an 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 application on my device, sans-serif-light is not applied in all views. For example, the TextViews in ActivityMain.java are displayed using the font I want, but in other actions like SecondActivity.java, all text objects are displayed normally. If I run my application on a device with Android 4.1, it works in every view. What am I doing wrong? Thanks in advance:)

+6
source share
1 answer

If using a 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 a material theme is important to 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 reload 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"); } } 
0
source

Source: https://habr.com/ru/post/978751/


All Articles