Last active
March 2, 2017 14:39
-
-
Save yyunikov/0ba97b40ff2dd3ff038b to your computer and use it in GitHub Desktop.
Android: overriding default fonts
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
/* | |
* 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