Saturday, October 3, 2015

Set Custom font using extended TextView Class

Make sure to put otf, ttf to your assets folder

I choose to put assets --> fonts(folder) --> custom.otf or ttf

import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;

public class TextViewCustoma extends TextView {
    public TextViewMonaBella(Context context) {
        super(context);
        setTypeface(context);
    }

    public TextViewMonaBella(Context context, AttributeSet attrs) {
        super(context, attrs);
        setTypeface(context);
    }

    public TextViewMonaBella(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setTypeface(context);
    }

    public void setTypeface(Context context) {
        Typeface face = Typeface.createFromAsset(context.getAssets(), "fonts/" + "custom.otf");
        this.setTypeface(face);
    }
}

and set to XML

<com.example.TextViewCustom
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

No comments:

Post a Comment