Skip to content

Instantly share code, notes, and snippets.

@AlexMeuer
Created September 6, 2017 10:23
Show Gist options
  • Save AlexMeuer/fb38958e1f154a0fef4e9738df83a49c to your computer and use it in GitHub Desktop.
Save AlexMeuer/fb38958e1f154a0fef4e9738df83a49c to your computer and use it in GitHub Desktop.
Basic extension of Android's TextView to allow declaring the use of custom fonts via xml. Assumes fonts are inside 'assets/fonts/' but this can be changed in `applyFont(..)`.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="CustomFontTextView">
<attr name="fontFile" format="string" />
</declare-styleable>
</resources>
package foo.bar.baz;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.support.annotation.NonNull;
import android.util.AttributeSet;
import foo.bar.R;
/**
* TextView that just uses a specified font file from 'assets/fonts/'.
* Specify the font in xml with 'fontFile="my-font.ttf"'
*/
public class CustomFontTextView extends android.support.v7.widget.AppCompatTextView {
public CustomFontTextView(Context context, AttributeSet attrs) {
super(context, attrs);
applyFont(attrs);
}
public CustomFontTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
applyFont(attrs);
}
private void applyFont(@NonNull AttributeSet attrs) {
final TypedArray attributes = getContext().obtainStyledAttributes(attrs, R.styleable.CustomFontTextView);
try {
final String fontFile = attributes.getString(R.styleable.CustomFontTextView_fontFile);
final Typeface font = Typeface.createFromAsset(getContext().getAssets(), "fonts/" + fontFile);
setTypeface(font, getTypeface().getStyle());
} finally {
attributes.recycle();
}
}
}
<foo.bar.baz.CustomFontTextView
android:id="@+id/foo_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="BAR!"
app:fontFile="Comic-Sans.ttf" />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment