Custom Font to make your App attractive

As I already discussed about this in my previous blog. Here let us see how to use them in listview and action bar title.

1) After creating custom adapter to your listview. Apply font at the end of getView method as of below

@Override

public View getView(int position, View convertView, ViewGroup parent)

{

..........

..........

// applying custom fonts

MyFont.applyFonts(convertView, Typeface.createFromAsset(context.getAssets(),"font/Purisa.ttf"));

return convertView;

}

Here applyFonts is a static method in seperate class as of below


public class MyFont {

public static void applyFonts(View v,Typeface fontToSet) {

try{

if(v instanceof ViewGroup){

ViewGroup vG = (ViewGroup)v;

for(int i = 0; i < vG.getChildCount();i++){

View child = vG.getChildAt(i);

applyFonts(child, fontToSet);

}

}else if (v instanceof TextView) {

((TextView)v).setTypeface(fontToSet);

}

} catch (Exception e) {

e.printStackTrace();

}

}

}

Applying custom font to actionbar is quite trickier, after doing lot of research I got this class which made it possible



// custom font to action bar title

public static class TypefaceSpan extends MetricAffectingSpan {

/** An <code>LruCache</code> for previously loaded typefaces. */

private static LruCache<String, Typeface> sTypefaceCache = new LruCache<String, Typeface>(12);

private Typeface mTypeface;

/*** Load the {@link Typeface} and apply to a {@link Spannable}.*/

public TypefaceSpan(Context context, String typefaceName) {

mTypeface = sTypefaceCache.get(typefaceName);

if (mTypeface == null) {

mTypeface = Typeface.createFromAsset(context.getApplicationContext().getAssets(),"font/Purisa.ttf");

// Cache the loaded Typeface

sTypefaceCache.put(typefaceName, mTypeface);

}

}

public TypefaceSpan(ActionBarDrawerToggle actionBarDrawerToggle,String typefaceName, Context context) {

mTypeface = sTypefaceCache.get(typefaceName);

if (mTypeface == null) {

mTypeface = Typeface.createFromAsset(context.getApplicationContext().getAssets(),"font/Purisa.ttf");

// Cache the loaded Typeface

sTypefaceCache.put(typefaceName, mTypeface);

}

}

@Override

public void updateMeasureState(TextPaint p) {

p.setTypeface(mTypeface);

// Note: This flag is required for proper typeface rendering

p.setFlags(p.getFlags() | Paint.SUBPIXEL_TEXT_FLAG);

}

@Override

public void updateDrawState(TextPaint tp) {

tp.setTypeface(mTypeface);

// Note: This flag is required for proper typeface rendering

tp.setFlags(tp.getFlags() | Paint.SUBPIXEL_TEXT_FLAG);

}

}

ApplySpannableStringBuilder to actionbar with custom font as below,


// applying purisa font to action bar

SpannableStringBuilder sBuilder = new SpannableStringBuilder(mTitle);

sBuilder.setSpan(new TypefaceSpan(this, "Purisa.ttf",getApplicationContext()), 0, sBuilder.length(),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

getActionBar().setTitle(sBuilder);

I hope this may help someone.

Enjoy ...!

Advertisements