Skip to content

Instantly share code, notes, and snippets.

@yyunikov
Last active March 2, 2017 14:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yyunikov/0ba97b40ff2dd3ff038b to your computer and use it in GitHub Desktop.
Save yyunikov/0ba97b40ff2dd3ff038b to your computer and use it in GitHub Desktop.
Android: overriding default fonts
/*
* Copyright 2014 Yuriy Yunikov
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import android.content.Context;
import android.graphics.Typeface;
import java.lang.reflect.Field;
/**
* @author yyunikov
*/
public final class FontsOverride {
public static void setDefaultFont(final Context context, final String staticTypefaceFieldName, final String fontAssetName) {
final Typeface regular = Typeface.createFromAsset(context.getAssets(),
fontAssetName);
replaceFont(staticTypefaceFieldName, regular);
}
protected static void replaceFont(final String staticTypefaceFieldName,
final Typeface newTypeface) {
try {
final Field staticField = Typeface.class
.getDeclaredField(staticTypefaceFieldName);
staticField.setAccessible(true);
staticField.set(null, newTypeface);
} catch (final NoSuchFieldException e) {
Logger.getInstance().error(Model.getInstance().getApplication(), "Error getting static field by reflection.", e);
} catch (final IllegalAccessException e) {
Logger.getInstance().error(Model.getInstance().getApplication(), "Error getting static field by reflection.", e);
}
}
}
//...
public void doSmth() {
FontsOverride.setDefaultFont(this, "MONOSPACE", "fonts/Roboto-Light.ttf");
FontsOverride.setDefaultFont(this, "SERIF", "fonts/Roboto-Regular.ttf");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment