Vins Vins - 5 months ago 33
Android Question

How to use custom font in android xml?

How can I use a custom font which was added in the asset folder in my xml? I know we can use

setTypeface()
method in java, but we have to do this everywhere where we use that
TextView
. So is there a better way?

Answer

The best way i found by googling is- Say if you want to use in TextView then we have to extend the Textview and have to set the font in that later we can use our customised Textview in our xml. I'll show the extended TextView below

package com.vins.test;

import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.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() {
        Typeface tf = Typeface.createFromAsset(getContext().getAssets(),
                                               "your_font.ttf");
        setTypeface(tf);
    }

}

We calling init() to set font in each of the costructors. Later we have to use this in our main.xml as shown below.

<com.vins.test.MyTextView
    android:id="@+id/txt"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:layout_weight="1"
    android:text="This is a text view with the font u had set in MyTextView class "
    android:textSize="30dip"
    android:textColor="#ff0000"
   >

Update:

Be aware about the memory leak in pre-4.0 Android as mentioned by pandre.

Comments