Tuesday, January 15, 2013

Custom Font for View

Hi developers,
today I want to show you how to set a custom font to a View either by code or using an XML file.
The first way is very simple: just copy the font file into "assets/fonts/"  folder and  load it using Typeface classcalling createFromAssets method.

















TextView txtView1 = (TextView) findViewById(R.id.textView1);
Typeface externalFont = Typeface.createFromAsset(getAssets(), "fonts/CONSOLA.TTF");
txtView1.setTypeface(externalFont);

Very simple! The hardest way is set custom Font using an XML file, especially by using styles!!
Yes it is possible! unlike what you read in various forums...
Just extremize the concept of custom view.
So the first thing to do is create a CustomView (in this case is a TextView but the concept is valid for all View), within a method to set the "Custom Font" that we call in the constructor of View:

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

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

    private void setCustomFont(Context ctx, AttributeSet attrs) {
        TypedArray a = ctx.obtainStyledAttributes(attrs, R.styleable.CustomFontTxtView);
        String customFont = a.getString(R.styleable.CustomFontTxtView_customFont);
        setCustomFont(ctx, customFont);
        a.recycle();
    }

    public boolean setCustomFont(Context ctx, String asset) {
        Typeface tf = null;
        try {
        tf = Typeface.createFromAsset(ctx.getAssets(), asset);  
        } catch (Exception e) {
            Log.e(TAG, "Error to get typeface: "+e.getMessage());
            return false;
        }
        setTypeface(tf);  
        return true;
    }

to be able to change from xml we need to create our style resources in this way:



    

And now we can set the font from layout XML file!!!:



    

    

    
    
    

Here you can download the complete example.



No comments :

Post a Comment