Alex Rivera | Logout

Android: Want to set custom fonts for whole application not runtime

Asked 2010-12-09T05:56:34.187
101

Is it possible to set any custom font in every control of the application? And not necessarily runtime ? (i.e. from xml if possible or only once for whole application in JAVA file)

I can set the font for one control from this code.

public static void setFont(TextView textView) {
    Typeface tf = Typeface.createFromAsset(textView.getContext()
            .getAssets(), "fonts/BPreplay.otf");

    textView.setTypeface(tf);

}

And the problem with this code is it should be called for every control. And i want to call this or any similar method once, or if possible set the property in xml. Is it possible?

Edit
Report

1 Answer

93

There is a fairly easy way to do this via XML. You just need to create your own widget that extends TextView.

First, create a file in res/values/attrs.xml with the following content:

<resources>
    <declare-styleable name="TypefacedTextView">
        <attr name="typeface" format="string" />
    </declare-styleable>
</resources>

After that, create your custom widget:

package your.package.widget;

public class TypefacedTextView extends TextView {

    public TypefacedTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        
        //Typeface.createFromAsset doesn't work in the layout editor. Skipping...
        if (isInEditMode()) {
            return;
        }
        
        TypedArray styledAttrs = context.obtainStyledAttributes(attrs, R.styleable.TypefacedTextView);
        String fontName = styledAttrs.getString(R.styleable.TypefacedTextView_typeface);
        styledAttrs.recycle();
        
        if (fontName != null) {
            Typeface typeface = Typeface.createFromAsset(context.getAssets(), fontName);
            setTypeface(typeface);
        }
    }

}

As you can see, the code above will read a font inside the assets/ folder. For this example, I am assuming that there is a file called "custom.ttf" in the assets folder. At last, use the widget in the XMLs:

<your.package.widget.TypefacedTextView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:your_namespace="http://schemas.android.com/apk/res/your.package"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Custom fonts in XML are easy"
    android:textColor="#FFF"
    android:textSize="14dip"
    your_namespace:typeface="custom.ttf" />

Note: Y

answered 2012-02-08T18:28:45.893

Your Answer