Skip to content

Instantly share code, notes, and snippets.

@AlexMeuer
Created February 5, 2018 13:53
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 AlexMeuer/dcb391ec6075d8804efff179f428acbd to your computer and use it in GitHub Desktop.
Save AlexMeuer/dcb391ec6075d8804efff179f428acbd to your computer and use it in GitHub Desktop.
Adaptation of https://gist.github.com/AlexMeuer/fb38958e1f154a0fef4e9738df83a49c for a single font. No need to add xml attributes for the same font everywhere if you can just swap out all the TextViews with a custom class.
package foo.bar.baz;
import android.content.Context;
import android.graphics.Typeface;
import android.support.annotation.IntDef;
import android.util.AttributeSet;
import com.google.common.collect.ImmutableMap;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* TextView that just uses the Lato font.
* Adapted from: https://gist.github.com/AlexMeuer/fb38958e1f154a0fef4e9738df83a49c
*/
public class LatoTextView extends android.support.v7.widget.AppCompatTextView {
private static final String FONTS_PATH = "fonts/";
private static ImmutableMap<Integer, String> styleMap = ImmutableMap.of(
Style.NORMAL, "Lato.ttf",
Style.BOLD, "Lato-Bold.ttf",
Style.LIGHT, "Lato-Light.ttf"
);
public LatoTextView(Context context) {
super(context);
}
public LatoTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public LatoTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Retention(RetentionPolicy.SOURCE)
@Target({ElementType.PARAMETER, ElementType.FIELD, ElementType.METHOD, ElementType.LOCAL_VARIABLE})
@IntDef({Style.NORMAL, Style.LIGHT, Style.BOLD})
public @interface Style {
int NORMAL = Typeface.NORMAL;
int LIGHT = Typeface.ITALIC; // We don't need italics, se we're overriding it with the Light version of the font.
int BOLD = Typeface.BOLD;
}
@Override
public void setTypeface(Typeface tf, @Style int style) {
super.setTypeface(Typeface.createFromAsset(
getContext().getAssets(),
FONTS_PATH+getFontPathForStyle(style)
));
}
public void setStyle(@Style int style) {
setTypeface(null, style);
}
private static String getFontPathForStyle(@Style int style) {
return styleMap.containsKey(style)
? styleMap.get(style)
: styleMap.get(Style.NORMAL);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment