package com.safemobile.uicomponents; import java.util.Hashtable; import com.safemobile.lib.R; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Typeface; import android.util.AttributeSet; import android.widget.TextView; public class EnhancedTextView extends TextView { private static final Hashtable cache = new Hashtable(); public EnhancedTextView(Context context) { super(context); } public EnhancedTextView(Context context, AttributeSet attrs) { super(context, attrs); setCustomFont(context, attrs); } public EnhancedTextView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); setCustomFont(context, attrs); } /** * Set a custom TypeFace that is specified in the XML attrs of the object * @param ctx The context of the application * @param attrs The attributes which are passed from the XML */ private void setCustomFont(Context ctx, AttributeSet attrs) { TypedArray a = ctx.obtainStyledAttributes(attrs, R.styleable.EnhancedTextView); String customFont = a.getString(R.styleable.EnhancedTextView_setFont); setCustomFont(ctx, customFont); a.recycle(); } /** * Function to change the TypeFace/Font of a textView * @param ctx The context of the application * @param fontName The name of the TypeFace which needs to be set * @return A boolean telling if the TypeFace was set, or false in case of error */ public boolean setCustomFont(Context ctx, String fontName) { Typeface tf = getTypeFace(ctx, fontName); if(tf == null) return false; setTypeface(tf); return true; } /** * In the Android versions previous than 4.0 there is a memory leak that won't free TypeFaces. * In order to fix this issue, a HashMap (cache) of TypeFaces will be created that will fetch a TypeFace * if it exists, or it will create it and then return it. * @param c The context of the application * @param fontName The name of the typeface which needs to be fetched * @return The desired Typeface object, or null if the typeface wasn't in the cache and could not be created */ public static Typeface getTypeFace(Context c, String fontName){ synchronized(cache){ if (cache == null || fontName == null) return null; if(!cache.containsKey(fontName)){ try { Typeface t = Typeface.createFromAsset(c.getAssets(), fontName); cache.put(fontName, t); } catch(Exception ex) { return null; } } return cache.get(fontName); } } }