bauer9664
bauer9664

Reputation: 117

Create Custom Font which one is better

I am new in android and I want use my custom font for my app. I wrote 2 ways creating custom font. Could you tell me guys which one is better and faster. first way is using singleton class second way is create my own textview.

with singleton

public class FontFactory {
    private  static FontFactory instance;
    private HashMap<String, Typeface> fontMap = new HashMap<String, Typeface>();

    private FontFactory() {
    }

    public static FontFactory getInstance() {
        if (instance == null){
            instance = new FontFactory();
        }
        return instance;
    }

    public Typeface getFont(DefaultActivity pActivity,String font) {
        Typeface typeface = fontMap.get(font);
        if (typeface == null) {
            typeface = Typeface.createFromAsset(pActivity.getResources().getAssets(), "fonts/" + font);
            fontMap.put(font, typeface);
        }
        return typeface;
    }
}

with own textview

public class MyTextView extends TextView {
    public MyTextView(Context context) {
        super(context);
    }

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

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

    private void setFonts(Context context, AttributeSet attrs){
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyTextView_customFont);
        String ttfName = a.getString(R.styleable.MyTextView_customFont_ttf_name);

        setCustomTypeFace(context, ttfName);
    }

    public void setCustomTypeFace(Context context, String ttfName) {
        Typeface font = Typeface.createFromAsset(context.getAssets(), "fonts/MuseoSansCyrl_"+ttfName+".otf");
        setTypeface(font);
    }
    @Override
    public void setTypeface(Typeface tf) {

        super.setTypeface(tf);
    }

}

Upvotes: 2

Views: 881

Answers (1)

Patrick
Patrick

Reputation: 4870

In your custom textview approach, you are creating the Typeface object every time you create a CustomTextView (or change its typeface), while your factory would keep the already loaded ones around in memory and re-use them.

The approach with a custom text view may work fine in some instances, but if you suddenly need to create a lot of them (or change the typeface on a lot of them), it might noticably slow down your performance as in this question with a scrollview.

I'd choose the singleton.

Upvotes: 1

Related Questions