Skip to content

Instantly share code, notes, and snippets.

@addam01
Created August 1, 2017 08:05
Show Gist options
  • Save addam01/92d843879fc1539b28c9f40699f179f4 to your computer and use it in GitHub Desktop.
Save addam01/92d843879fc1539b28c9f40699f179f4 to your computer and use it in GitHub Desktop.
Android Custom Textview
<declare-styleable name="CustomTextView">
<attr name="fontName" format="string" />
</declare-styleable>
public class CustomTextView extends TextView {
public CustomTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(attrs);
}
public CustomTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs);
}
public CustomTextView(Context context) {
super(context);
init(null);
}
private void init(AttributeSet attrs) {
if (attrs!=null) {
TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.CustomTextView);
String fontName = a.getString(R.styleable.CustomTextView_fontName);
if (fontName!=null) {
Typeface myTypeface = Typeface.createFromAsset(getContext().getAssets(), "fonts/"+fontName);
setTypeface(myTypeface);
}
a.recycle();
}
}
}
<com.abc.someclass.CustomTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:fontName="/*name of your font from assets/font folder*/"/>
@addam01
Copy link
Author

addam01 commented Aug 1, 2017

  1. Create asset resource
  2. Copy Pasta your custom font file into the asset
  3. Create the Java class handler for custom text view
  4. Declare in the attrs.xml
  5. Use the custom in activity xml

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment