Use external fonts in android


Answers

In order to access our font easily, we need to bundle it with our application in a way that our code can subsequently load it. To do this, we create a Fonts folder in our assets direct

This may be your .xml

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
    android:id="@+id/DefaultFontText"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textSize="30sp"
    android:text="Here is some text." />
<TextView
    android:id="@+id/CustomFontText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="30sp"
    android:text="Here is some text.">
    </TextView>

Write following code in your .java class

Typeface tf = Typeface.createFromAsset(getAssets(),
            "fonts/BPreplay.otf");
    TextView tv = (TextView) findViewById(R.id.CustomFontText);
    tv.setTypeface(tf);
Question

I want to use external fonts in my app. I have tried adding new fonts using AssetManager but it did not work. Below is my code:

Typeface face;

face = Typeface.createFromAsset(getAssets(), "font.otf");

textview.setTypeface(face);

but its not showing the text...

Please help me with this.




You include a custom font to make your app look pretty, stand out from the crowd, conform to some brand identity etc. Also, packaging your own font gives you ultimate control. Manufacturers are free to change the standard themes (including fonts) for their own skins e.g. HTC Sense, Samsung TouchWiz etc).

The only real downsides are that you must include the custom font within your apk (which adds to the download size) and that you need boilerplate code in every activity that uses your custom font (i.e. you cannot simply assign your custom font to a textview/edittext etc via xml).

Older versions of Android (i.e. <1.6) may not support your font but as of today that's <0.6% of the market. http://developer.android.com/resources/dashboard/platform-versions.html







To use or not to use Custom Fonts on Android

In addition to the downsides cited by the existing answers, also consider:

  • you need a font that you are legally allowed to distribute
  • you need a font that has all the right glyphs for all the languages you intend to support (not all fonts do)
  • in my experience, Android can't handle every font and quietly falls back to Droid Sans for those it does not support, so you will need to test your font to ensure it actually works



What font file types does Android support?

Android docs doesn't specify the fonts that it supports.When Android dislikes a custom font, rather than raising an Exception, it seems to substitute Droid Sans ("sans").







Tags