Skip to content

Instantly share code, notes, and snippets.

@demixdn
Created March 1, 2017 12:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save demixdn/153aaefeeeddc965f5a3e58251350160 to your computer and use it in GitHub Desktop.
Save demixdn/153aaefeeeddc965f5a3e58251350160 to your computer and use it in GitHub Desktop.
import android.content.Context;
import android.graphics.Typeface;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.StringDef;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.ref.WeakReference;
import java.util.HashMap;
/**
* @author demixdn
*/
@SuppressWarnings("unused")
public class AppTypeface {
@StringDef({Roboto.LIGHT, Roboto.REGULAR})
@Retention(RetentionPolicy.SOURCE)
@interface Font {
}
public static final class Roboto {
public static final String LIGHT = "Roboto-Light.ttf";
public static final String REGULAR = "Roboto-Regular.ttf";
private Roboto() {
//only private
}
}
private final HashMap<String, Typeface> typefaceHashMap;
private final WeakReference<Context> context;
public AppTypeface(@NonNull Context context) {
this.context = new WeakReference<>(context);
this.typefaceHashMap = new HashMap<>();
}
/**
* HashMap usage for storage typeface. Clear that in clear();
*
* @param fontName - Must be one of {@link Roboto}.
* @return {@link Typeface} from assets by 'fontName' name.
* Default return Roboto-Regular
*/
@Nullable
public Typeface get(@NonNull @Font String fontName) {
return getTypeFace(context.get(), fontName);
}
@Nullable
private Typeface getTypeFace(@Nullable Context context, @NonNull String type) {
Typeface current = typefaceHashMap.get(type);
if (context == null)
return null;
if (current != null)
return current;
return createTypeface(context, type);
}
private Typeface createTypeface(@NonNull Context context, @NonNull String type) {
Typeface current;
try {
current = Typeface.createFromAsset(context.getAssets(), type);
typefaceHashMap.put(type, current);
return typefaceHashMap.get(type);
} catch (Exception ignored) {
return Typeface.createFromAsset(context.getAssets(), Roboto.REGULAR);
}
}
/**
* Clear typeface storage.
*/
public void clear() {
typefaceHashMap.clear();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment