replace Typeface - Android Graphics

Android examples for Graphics:Font

Description

replace Typeface

Demo Code


//package com.java2s;
import android.content.Context;
import android.graphics.Typeface;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.HashMap;
import java.util.Map;

public class Main {
    private static final Map<String, Typeface> sTypefaceCache = new HashMap<String, Typeface>();

    public static void replaceTypeface(Context c, View v, String filepath) {
        if (v instanceof TextView) {
            TextView txtView = (TextView) v;
            int style = Typeface.NORMAL;
            if (txtView.getTypeface() != null) {
                style = txtView.getTypeface().getStyle(); 
            }/*  w w w . j av  a 2  s .c o  m*/
            txtView.setTypeface(loadTypeface(c, filepath), style);
        } else if (v instanceof ViewGroup) {
            ViewGroup vg = (ViewGroup) v;
            for (int i = 0; i < vg.getChildCount(); ++i) {
                replaceTypeface(c, vg.getChildAt(i), filepath);
            }
        }
    }

    private static Typeface loadTypeface(Context c, String filepath) {
        Typeface tf = sTypefaceCache.get(filepath);
        if (tf == null) {
            tf = Typeface.createFromAsset(c.getAssets(), filepath);
            sTypefaceCache.put(filepath, tf);
        }
        return tf;
    }
}

Related Tutorials