Loads the font directly from the Assets. - Android Graphics

Android examples for Graphics:Font

Description

Loads the font directly from the Assets.

Demo Code


//package com.java2s;
import android.content.Context;
import android.graphics.Typeface;
import android.util.Log;

public class Main {
    /**//from   w w  w. j  a v  a2 s.c o  m
     * Loads the font directly from the Assets. No caching done here.
     * @param context
     * @param fontFamily
     * @return The loaded Typeface or null if failed.
     */
    private static Typeface loadFontFromAssets(Context context,
            String fontFamily) {
        if (!fontFamily.contains(".") && !fontFamily.contains("/")) {
            String ttfFontFamily = "fonts/" + fontFamily + ".ttf";

            try {
                return Typeface.createFromAsset(context.getResources()
                        .getAssets(), ttfFontFamily);
            } catch (Exception ignored) {
            }

            String otfFontFamily = "fonts/" + fontFamily + ".otf";

            try {
                return Typeface.createFromAsset(context.getResources()
                        .getAssets(), otfFontFamily);
            } catch (Exception ignored) {
            }
        }

        try {
            return Typeface.createFromAsset(context.getResources()
                    .getAssets(), fontFamily);
        } catch (Exception e) {
            Log.e("FontHelper", e.getMessage());
            return null;
        }
    }
}

Related Tutorials