Skip to content

Instantly share code, notes, and snippets.

@alphamu
Last active December 29, 2015 12:09
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 alphamu/7668288 to your computer and use it in GitHub Desktop.
Save alphamu/7668288 to your computer and use it in GitHub Desktop.
A textview that can use a custom font without having to set it in code all the time
public class TextViewWithFont extends TextView {
private Context mContext;
private String mFont;
public TextViewWithFont(Context context) {
super(context, null);
mContext = context;
init();
}
public TextViewWithFont(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
TypedArray a = context.getTheme().obtainStyledAttributes(
attrs,
R.styleable.CustomButtom,
0, 0);
try {
mFont = a.getString(R.styleable.TextViewWithFont_font);
} finally {
a.recycle();
}
init();
}
private void init() {
if (mFont != null) {
Typeface tf = Typeface.createFromAsset(getContext().getAssets(), mFont);
setTypeface(tf);
}
}
}
/*
//attr.xml
<declare-styleable name="TextViewWthFont">
<attr name="font" format="string" />
</declare-styleable>
//layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res/com.package.name.widget"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<com.package.name.widget.TextViewWthFont
android:layout_width="wrap_content"
android:layout_height="wrap_content"
custom:font="font/myfont.ttf"
android:text="@string/test" />
</LinearLayout>
//place font file under assets/font/
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment