user2680801
user2680801

Reputation: 89

Change the font of all the textviews in my application?

I wonder if there is a way to change the font of all the text views in an android application in single time ? By all the text views i mean programmatically or dynamically created text views and the text views created separately using XML layout files (Drag n drop)?

I know i can create a new theme with different required fonts and use it . But i can only see the theme applies to dynamically created text views within the program but not the one's in XML layout .

Can you please let me know if there is any solution for this or the only option is to change the font of each text view manually.

Upvotes: 0

Views: 202

Answers (1)

IsaacCisneros
IsaacCisneros

Reputation: 1953

The easiest way is to extend the TextView widget:

public class FontTextView extends TextView {

private String mTypefacePath;

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

public FontTextView(Context context, AttributeSet attrs) {
    super(context, attrs);
    setAttrs(context, attrs, 0);
    init(context);
}

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

private void setAttrs(Context context, AttributeSet attrs, int defStyle) {
    if (isInEditMode())
        return;
    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.FontTextView, defStyle, 0);
    mTypefacePath = a.getString(R.styleable.FontTextView_typeface);
    a.recycle();
}

private void init(Context context) {
    if (!TextUtils.isEmpty(mTypefacePath)) {
        try {
            setTypeface(Typeface.createFromAsset(context.getAssets(),
                    mTypefacePath));
        } catch (Exception ex) {
            // could not create the typeface from path
        }
    } 
}}

You also need to define your typeface attribute. Take a look on this to see a useful explanation about.

Upvotes: 2

Related Questions