Skip to content

Instantly share code, notes, and snippets.

@rajohns08
Last active May 1, 2016 19:46
Show Gist options
  • Save rajohns08/6c4acf0b5c829d175e6ea55c54fd02ee to your computer and use it in GitHub Desktop.
Save rajohns08/6c4acf0b5c829d175e6ea55c54fd02ee to your computer and use it in GitHub Desktop.
Android - Custom view attributes with a custom font
  1. Download Permanent Marker font from random internet site: https://www.fontsquirrel.com/fonts/permanent-marker
  2. Copy the PermanentMarker.ttf file into assets directory (should be the same level as res directory NOT inside res directory). You may have to create the assets directory yourself in Finder.
  3. The attrs.xml file below should be in /res/values/
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.your.package.CustomFontTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/take_a_photo"
android:textSize="40sp"
app:font="PermanentMarker" />
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="CustomFontTextView">
<attr name="font" format="string"/>
</declare-styleable>
</resources>
public class CustomFontTextView extends TextView {
public CustomFontTextView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.CustomFontTextView, 0, 0);
try {
String fontName = ta.getString(R.styleable.CustomFontTextView_text_font);
this.setTypeface(Font.fromString(context, fontName));
} finally {
ta.recycle();
}
}
}
public class Font {
public static Typeface fromString(Context context, String fontName) {
if (fontName == null) {
return Typeface.DEFAULT;
}
Typeface font = Typeface.createFromAsset(context.getApplicationContext().getAssets(), fontName + ".ttf");
return font == null ? Typeface.DEFAULT : font;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment