Last active
August 29, 2015 14:07
-
-
Save ramannanda9/0bfe60d7ae4baf81e755 to your computer and use it in GitHub Desktop.
Override fonts application wide in android.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.blogspot.ramannanda.apps.simplyread.utils; | |
import android.content.Context; | |
import android.graphics.Typeface; | |
import android.renderscript.Font; | |
import android.util.Log; | |
import java.lang.reflect.Field; | |
public class TypefaceUtil { | |
private static final String tag=TypefaceUtil.class.getName(); | |
/** | |
* Using reflection to override default typeface | |
* In case you want to use default font just pass true to the method | |
* NOTICE: DO NOT FORGET TO SET TYPEFACE FOR APP THEME AS DEFAULT TYPEFACE WHICH WILL BE OVERRIDDEN | |
* @param context to work with assets | |
* @param defaultFontNameToOverride for example "monospace" | |
* @param customFontFileNameInAssets file name of the font from assets | |
*/ | |
public static Typeface overrideFont(Context context, String defaultFontNameToOverride, String customFontFileNameInAssets, boolean isDefault) { | |
Typeface customFontTypeface=null; | |
try { | |
if(isDefault){ | |
customFontTypeface = Typeface.create((Typeface)null,Typeface.NORMAL); | |
} | |
else{ | |
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(tag,"Can not set custom font " + customFontFileNameInAssets + " instead of " + defaultFontNameToOverride,e); | |
} | |
return customFontTypeface; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment