Skip to content

Instantly share code, notes, and snippets.

@dominicbartl
Last active August 29, 2015 14:04
Show Gist options
  • Save dominicbartl/84a29417da10ed032942 to your computer and use it in GitHub Desktop.
Save dominicbartl/84a29417da10ed032942 to your computer and use it in GitHub Desktop.
Android TextView with font set by XML
<resources>
<declare-styleable name="TypedTextView">
<attr name="typeface" format="string" />
</declare-styleable>
</resources>
package com.playquickly.ui.widget;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;
import com.playquickly.R;
@SuppressWarnings("unused")
public class TypedTextView extends TextView {
public TypedTextView(Context context) {
super(context);
}
public TypedTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs);
}
public TypedTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(attrs);
}
public void setFont(String fontAsset, int style) {
Typeface font = Typeface.createFromAsset(getContext().getAssets(), fontAsset);
setTypeface(font, style);
}
private void init(AttributeSet attrs) {
if (!isInEditMode()) {
TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.TypedTextView);
String typeface = a.getString(R.styleable.TypedTextView_typeface);
setFont(typeface, Typeface.NORMAL);
a.recycle();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment