Created
November 9, 2016 01:06
-
-
Save daolq3012/bc20f1d6492a2724778ed1c397982fea to your computer and use it in GitHub Desktop.
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
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(); | |
} | |
} | |
} |
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
in attrs.xml thêm: