Skip to content

Instantly share code, notes, and snippets.

@daolq3012
Created November 9, 2016 01:06
Show Gist options
  • Save daolq3012/bc20f1d6492a2724778ed1c397982fea to your computer and use it in GitHub Desktop.
Save daolq3012/bc20f1d6492a2724778ed1c397982fea to your computer and use it in GitHub Desktop.
public class TextViewCustomFont extends TextView {
private static final String TAG = TextViewCustomFont.class.getSimpleName();
public TextViewCustomFont(Context context) {
super(context);
initProperties(null);
}
public TextViewCustomFont(Context context, AttributeSet attrs) {
super(context, attrs);
initProperties(attrs);
}
public TextViewCustomFont(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initProperties(attrs);
}
private void initProperties(AttributeSet attrs) {
setIncludeFontPadding(false);
if (attrs == null) {
return;
}
TypedArray typedArray =
getContext().obtainStyledAttributes(attrs, R.styleable.TextViewCustomFont);
try {
String fontName = typedArray.getString(R.styleable.TextViewCustomFont_font);
if (!isInEditMode()) {
Typeface typeface = FontCache.getFont(fontName, getContext());
setTypeface(typeface);
setPaintFlags(getPaintFlags() | Paint.SUBPIXEL_TEXT_FLAG);
}
} catch (Throwable e) {
Log.d(TAG, e.getMessage());
} finally {
typedArray.recycle();
}
}
}
@daolq3012
Copy link
Author

in attrs.xml thêm:

<declare-styleable name="TextViewCustomFont">
        <attr format="string" name="font"/>
    </declare-styleable>

@daolq3012
Copy link
Author

public class FontCache {

    private static LruCache<String, Typeface> mFontCache = new LruCache<>(12);

    public static Typeface getFont(String fontName, Context context) {
        if (StringUtils.isBlank(fontName)) {
            fontName = context.getString(R.string.font_hirakaku_pro_n_w3);
        }
        Typeface typeface = mFontCache.get(fontName);
        if (typeface == null) {
            try {
                typeface = Typeface.createFromAsset(context.getApplicationContext().getAssets(),
                        "fonts/" + fontName);
            } catch (Exception e) {
                return null;
            }
            mFontCache.put(fontName, typeface);
        }
        return typeface;
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment