Thursday 4 July 2013

Custom Font Text view and Button for Android.

Hi All,

By this post we are going to learn about how to implement the custom fornt for textviews and Buttons.  I am going to teach you the very simple method to do it.


Step 1.

Use this class for Custom Font Text view style.
 Download your ttf file and paste it in your assests folder.

import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;

public class CustomFontTextView extends TextView {

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

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

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

    private void init() {
        Typeface tf = Typeface.createFromAsset(getContext().getAssets(),
                                            "your font.ttf");
        setTypeface(tf);
    }

}

Step 2 

then define your text view like below.

<com.example.customfont.CustomFontTextView
                        android:layout_width="fill_parent"
                        android:layout_height="wrap_content" 
                        android:text="Custom Font Test"
                        android:textStyle="normal" />

For Button  Your Custom Class should entends Button instead of Text View.
So your code should be something like below.


import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.Button;
import android.widget.TextView;

public class CustomFontButton extends Button {

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

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

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

    private void init() {
        Typeface tf = Typeface.createFromAsset(getContext().getAssets(),
                                               "Roboto-Light.ttf");
        setTypeface(tf);
    }

}


There is no need to mention your custom font TextView/Button  any where else . This will work fine. Happy coding.

1 comment:

Unknown said...

THank u buddy ur code help me . its really good thank u