Wednesday, 22 June 2016

Custom Font in Android

In this post we will be learning how to use custom fonts in your project. First i will mention all the necessary steps to do it and then we will check code explanation for complex methods.

Step 1: Download below files and integrate them in your project:
  1. TypeFaceHelper.java
  2. CustomTextView.java
Step 2: Create attrs.xml (if not present) under your res/values folder. Place below code
<?xml version="1.0" encoding="utf-8"?>
<resources>
  <declare-styleable name="CustomTextView">
        <attr name="fontFace" format="string" />
    </declare-styleable>
</resources>
Step 3: Download Custom Fonts. You can use any custom font which you need I have used arial.ttf fonts you can download it from below links
  1. arial.ttf
  2. arial_bold.ttf

Step 4: Place Custom fonts under your assets folder like this
              
Step 5: Refer them in your strings.xml like
      <!-- Fonts -->
          <string name="fonts_normal">arial.ttf</string>
          <string name="fonts_bold">arial_bold.ttf</string>
Step 6: You can use above custom type face in your layout xmls like below:
 <package.name.CustomTextView

        xmlns:coop="http://schemas.android.com/apk/res-auto"
        style="@style/title_font_gray"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        coop:fontFace="@string/fonts_normal" />
 Its Done, Hopefully you can easily integerate this in your projects.

Explainations:
  • TypeFaceHelper- This class allows you to load fonts from your assets directory.
  • CustomTextView- This class takes care to set typeface on your custom textviews. This class also set default typeface or normal font if fontface is not provided in your layout xml. Below lines of code take care of it.

  String fontFace = typedArray.getString(R.styleable.CustomTextView_fontFace);
            if (fontFace == null) {
                fontFace = context.getString(R.string.fonts_normal);
            }
  • CustomTextView class also has some helper methods like- 
    public void useBoldFont(){
        String fontFace = getContext().getString(R.string.fonts_bold);
        setTypeface(TypefaceHelper.getTypeface(getContext(), fontFace));
    }

    public void useNormalFont(){
        String fontFace = getContext().getString(R.string.fonts_normal);
        setTypeface(TypefaceHelper.getTypeface(getContext(), fontFace));
    }
 You can use above methods directly from your code without updating layout xml file.


Happy Coding ...