Skip to content

Instantly share code, notes, and snippets.

@Mariovc
Last active March 3, 2020 05:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Mariovc/fb8c5224323c0bdcdd13 to your computer and use it in GitHub Desktop.
Save Mariovc/fb8c5224323c0bdcdd13 to your computer and use it in GitHub Desktop.
Cache your created typefaces to avoid memory leaks.
public enum Font {
OXYGEN_REGULAR("Oxygen-Regular.ttf"),
OXYGEN_LIGHT("Oxygen-Light.ttf"),
OXYGEN_BOLD("Oxygen-Bold.ttf"),
GOTHAM_BOOK("Gotham-Book.ttf"),
GOTHAM_LIGHT("Gotham-Light.ttf"),
GOTHAM_MEDIUM("Gotham-Medium.ttf");
private final String path;
Font(String str) {
this.path = str;
}
public String getPath() {
return path;
}
}
import android.content.Context;
import android.graphics.Typeface;
import android.support.design.widget.TextInputLayout;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import java.util.Arrays;
import java.util.HashMap;
public class FontManager {
private static final String TAG = "FontManager";
private static FontManager instance;
private final Context context;
private final HashMap<Font, Typeface> map = new HashMap<Font, Typeface>();
private FontManager(Context context) {
this.context = context.getApplicationContext();
}
public static FontManager getInstance(Context ctx) {
if (instance == null) {
instance = new FontManager(ctx);
}
return instance;
}
public void setTypeface(Font font, View... textableViews) {
for (View v : textableViews) {
if (v != null) {
if (v instanceof TextView) {
((TextView) v).setTypeface(getTypeface(font));
} else if (v instanceof TextInputLayout) {
((TextInputLayout) v).setTypeface(getTypeface(font));
} else if (v instanceof CollapsingToolbarLayout) {
((CollapsingToolbarLayout) v).setCollapsedTitleTypeface(getTypeface(font));
((CollapsingToolbarLayout) v).setExpandedTitleTypeface(getTypeface(font));
}
} else {
Log.e(TAG, "Some views are null in the array: " + Arrays.toString(textableViews));
}
}
}
public Typeface getTypeface(Font font) {
Typeface typeface;
if (map.containsKey(font)) {
typeface = map.get(font);
} else {
typeface = Typeface.createFromAsset(context.getAssets(), font.getPath());
map.put(font, typeface);
}
return typeface;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment