Add custom font for complete android application

I figured it out by my self. This is the code I used. I create custom TextView which has custom font as default font.

public class MyTextView extends TextView {

    public MyTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    public MyTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public MyTextView(Context context) {
        super(context);
        init();
    }

    private void init() {
        Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "font/chiller.ttf");
        setTypeface(tf ,1);

    }

}

In your activities, right after you call

setContentView(R.id.blahblah);

you should run a method to go over the whole hierarchy of widgets and deal with the font substitution, like;

setContentView(R.id.blahblah);
Utils.overrideFonts(this, findViewById(android.R.id.content));

And the mentioned "overrideFonts" method should be something like;

public static void overrideFonts(final Context context, final View v) {
    try {
        if (v instanceof ViewGroup) {
            ViewGroup vg = (ViewGroup) v;
            for (int i = 0; i < vg.getChildCount(); i++) {
                View child = vg.getChildAt(i);
                overrideFonts(context, child);
            }
        } else if (v instanceof TextView) {
            ((TextView)v).setTypeface(FONT_REGULAR);
        }
    } catch (Exception e) {
        e.printStackTrace();
        // ignore
    }
}

In this scheme, FONT_REGULAR should be initialized somewhere safely, you may fancy a singleton or some other way to be sure that it is initialized properly...

private static void initializeFonts(final Context context) {
    FONT_REGULAR = Typeface.createFromAsset(context.getAssets(), "fonts/myfont_medium.otf");
    FONT_BOLD = Typeface.createFromAsset(context.getAssets(), "fonts/myfont_bold.otf");
}

If you use a subclass of Activity like MyAppActivity (extends Activity), then you dont need to change each and every Activity class for such customizations. Instead you may cut into it and override the behavior as such;

public class MyAppActivity extends Activity {
... ...
    @Override
    public void setContentView(final int layoutResID) {
        super.setContentView(layoutResID);
        Utils.overrideFonts(this, findViewById(android.R.id.content));
    }
... ...
}

This way you can use any activity of yours to have common behavior;

public class SettingsUI extends MyAppActivity {
... ...
} 

I hope it helps... Cheers!


create a style and use it all text attributes.

<style name="CustomText">
    <item name="android:typeface">YourFontName</item>
</style>

Use it:

<TextView style="@style/CustomText" />

Above is to use custom fonts in all activity for customization you can use....

Typeface font = Typeface.createFromAsset(getAssets(), "CustomFontName.ttf");  
txt.setTypeface(font);

TRy this.