Snippets

Muhammed Ballan Text view that allow you to change the font easily

Created by Muhammed Ballan
import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;

/**
 * Created by MBH on 12/5/2015.
 */

public class MBTextViewWithFont extends TextView {
    private String fontName;

    public MBTextViewWithFont(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

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

    public MBTextViewWithFont(Context context) {
        super(context);
    }

    // MB Functions
    public MBTextViewWithFont(Context context, String fontName) {
        super(context);
        this.fontName = fontName;
        setFontItem();
    }

    /**
     * The font file should be inside assets/fonts folder in order to get it working well
     */
    private void setFontItem(){
        if(fontName != null) {
            try{ // this try catch implemented in order to prevent app from crashing on any error
                // Please try to implement your error handling methods instead of Try Catch block
                Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "fonts/" + fontName);
                setTypeface(tf);
            } catch (Exception e){}
        }
    }

    public void setFont(String font) {
        if (font == null || font.equals(fontName)) {
            return;
        }
        fontName = font;
        setFontItem();
    }
}

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.