Skip to content

Instantly share code, notes, and snippets.

@afeozzz
Last active September 13, 2016 12:15
Show Gist options
  • Save afeozzz/65e95c67a840f64ca72cf4d1428e07d7 to your computer and use it in GitHub Desktop.
Save afeozzz/65e95c67a840f64ca72cf4d1428e07d7 to your computer and use it in GitHub Desktop.
CustomTextView
<declare-styleable name="CustomTextView">
<attr name="customFont" format="string" />
</declare-styleable>
public class CustomTextView extends TextView {
static Typeface defaultTypeface = Typeface.createFromAsset(App.getAppContext().getAssets(),
App.getAppContext().getString(R.string.font_regular));
public CustomTextView(Context context) {
super(context);
setTypeface(defaultTypeface);
}
public CustomTextView(Context context, AttributeSet attrs) {
super(context, attrs);
setCustomFont(context, attrs);
}
public CustomTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
setCustomFont(context, attrs);
}
private void setCustomFont(Context ctx, AttributeSet attrs) {
TypedArray a = ctx.obtainStyledAttributes(attrs, R.styleable.CustomTextView);
String customFont = a.getString(R.styleable.CustomTextView_customFont);
setCustomFont(ctx, customFont);
a.recycle();
}
public boolean setCustomFont(Context ctx, String asset) {
Typeface tf;
try {
if (asset != null) {
tf = Typeface.createFromAsset(ctx.getAssets(), asset);
} else {
tf = defaultTypeface;
}
} catch (Exception e) {
return false;
}
setTypeface(tf);
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment