Android How to integrate Icon fonts


Example

In order to use icon fonts, just follow the steps below:

  • Add the font file to your project

    You may create your font icon file from online websites such as icomoon, where you can upload SVG files of the required icons and then download the created icon font. Then, place the .ttf font file into a folder named fonts (name it as you wish) in the assets folder:

    Location where to put the font file

  • Create a Helper Class

    Now, create the following helper class, so that you can avoid repeating the initialisation code for the font:

    public class FontManager {
      public static final String ROOT = "fonts/";
      FONT_AWESOME = ROOT + "myfont.ttf";
      public static Typeface getTypeface(Context context) {
        return Typeface.createFromAsset(context.getAssets(), FONT_AWESOME);
      }
    }
    

    You may use the Typeface class in order to pick the font from the assets. This way you can set the typeface to various views, for example, to a button:

    Button button=(Button) findViewById(R.id.button);
    Typeface iconFont=FontManager.getTypeface(getApplicationContext());
    button.setTypeface(iconFont);
    

    Now, the button typeface has been changed to the newly created icon font.

  • Pick up the icons you want

    Open the styles.css file attached to the icon font. There you will find the styles with Unicode characters of your icons:

    .icon-arrow-circle-down:before {
      content: “\e001”;
    }
    .icon-arrow-circle-left:before {
      content: “\e002”;
    }
    .icon-arrow-circle-o-down:before {
      content: “\e003”;
    }
    .icon-arrow-circle-o-left:before {
      content: “\e004”;
    }
    

    This resource file will serve as a dictionary, which maps the Unicode character associated with a specific icon to a human-readable name. Now, create the string resources as follows:

    <resources>
      <! — Icon Fonts -->
      <string name=”icon_arrow_circle_down”>&#xe001; </string>
      <string name=”icon_arrow_circle_left”>&#xe002; </string>
      <string name=”icon_arrow_circle-o_down”>&#xe003; </string>
      <string name=”icon_arrow_circle_o_left”>&#xe004; </string>
    </resources>
    
  • Use the icons in your code

    Now, you may use your font in various views, for example, as follows:

    button.setText(getString(R.string.icon_arrow_circle_left))
    

    You may also create button text views using icon fonts:

    Example buttons with icons on them