apply Font to nested View - Android Graphics

Android examples for Graphics:Font

Description

apply Font to nested View

Demo Code


import android.content.Context;
import android.graphics.Typeface;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class Main{
    private static final String TAG = FontHelper.class.getSimpleName();
    private static String DEFAULT_NORMAL_FONT_FILENAME = "fonts/Play-Regular.ttf";
    private static String DEFAULT_BOLD_FONT_FILENAME = "fonts/Play-Bold.ttf";
    public static void applyFont(final Context context, final View root) {
        try {/*  ww  w . j  ava2s.  c  om*/
            if (root instanceof ViewGroup) {
                ViewGroup viewGroup = (ViewGroup) root;
                int childCount = viewGroup.getChildCount();
                for (int i = 0; i < childCount; i++)
                    applyFont(context, viewGroup.getChildAt(i));
            } else if (root instanceof TextView) {
                //if the font is bold then apply Play-Bold 
                if (((TextView) root).getTypeface() == Typeface.DEFAULT_BOLD) {
                    ((TextView) root)
                            .setTypeface(Typeface.createFromAsset(
                                    context.getAssets(),
                                    DEFAULT_BOLD_FONT_FILENAME));
                } else {
                    //if the font is normal then apply Play-Regular 
                    ((TextView) root).setTypeface(Typeface.createFromAsset(
                            context.getAssets(),
                            DEFAULT_NORMAL_FONT_FILENAME));
                }
            }
        } catch (Exception e) {
            Log.e(TAG,
                    String.format(
                            "Error occured when trying to apply %s font for %s view",
                            "", root));
            e.printStackTrace();
        }
    }
}

Related Tutorials