Last active
December 29, 2015 12:09
-
-
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
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 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