Reputation: 113
Devices like Samsung
allows users to set custom system fonts
. Issue is that those fonts can be overriding my app fonts
. I mean if I set Arial
font
in my app and I've set Calibri
font as system font
on my mobile then Arial
will be overridden by the Calibri font
.
How to prevent this situation?
Upvotes: 1
Views: 2210
Reputation: 9153
- "If you need to set one font for all
TextView's
in yourAndroid
application you can use this solution.It will override ALL
TextView's
typefaces, including theAction Bar
, custom system fonts and other standard components, butEditText's
password font won't be overridden." (For obvious reasons).Using
reflection
to override default typeface and theApplication
class.- NOTE: DO NOT FORGET TO SET TYPEFACE FOR APP THEME AS DEFAULT TYPEFACE WHICH WILL BE OVERRIDDEN
MyApp.java:
public class MyApp extends Application {
@Override
public void onCreate() {
TypefaceUtil.overrideFont(getApplicationContext(), "SERIF", "fonts/Roboto-Regular.ttf"); // font from assets: "assets/fonts/Roboto-Regular.ttf
}
}
res/themes.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="MyAppTheme" parent="@android:style/Theme.Holo.Light">
<!-- you should set typeface which you want to override with TypefaceUtil -->
<item name="android:typeface">serif</item>
</style>
</resources>
TypefaceUtil.java:
import android.content.Context;
import android.graphics.Typeface;
import android.util.Log;
import java.lang.reflect.Field;
public class TypefaceUtil {
/**
* Using reflection to override default typeface
* 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 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("Can not set custom font " + customFontFileNameInAssets + " instead of " + defaultFontNameToOverride);
}
}
}
assets/fonts/Roboto-Regular.ttf:
Put your font here e.g. Arial
.
Author Artem Zinnatullin
Upvotes: 3