Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set font for all textViews in activity?

Is it possible to set the font for all the TextViews in a activity? I can set the font for a single textView by using:

    TextView tv=(TextView)findViewById(R.id.textView1); 
    Typeface face=Typeface.createFromAsset(getAssets(), "font.ttf"); 
    tv.setTypeface(face);

But I would like to change all the textViews at once, instead of setting it manually for every textView, any info would be appreciated!

like image 788
William L. Avatar asked May 26 '12 13:05

William L.


2 Answers

Solution1:: Just call these method by passing parent view as argument.

private 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(Typeface.createFromAsset(context.getAssets(), "font.ttf"));
        }
    } catch (Exception e) {
 }
 }

Solution2:: you can subclass the TextView class with your custom font and use it instead of textview.

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() {
        if (!isInEditMode()) {
            Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "font.ttf");
            setTypeface(tf);
        }
    }

}
like image 135
Shankar Agarwal Avatar answered Oct 21 '22 13:10

Shankar Agarwal


The one from my personal collection:

private void setFontForContainer(ViewGroup contentLayout) {
    for (int i=0; i < contentLayout.getChildCount(); i++) {
        View view = contentLayout.getChildAt(i);
        if (view instanceof TextView)
            ((TextView)view).setTypeface(yourFont);
        else if (view instanceof ViewGroup)
            setFontForContainer((ViewGroup) view);
    }
}
like image 8
Red Hot Chili Coder Avatar answered Oct 21 '22 13:10

Red Hot Chili Coder