Pages

Saturday, October 1, 2011

Using Custom Fonts With Android

I was messing around and figured out how to use custom fonts in your Android application. It's really simple so this will be a quick and dirty how-to...

Custom fonts use the TypeFace class.

First find yourself a nice font... I found and will use this one here called "Cheyenne Hand" at 1001 Free Fonts.

After downloading and unzipping the file, add the ttf font file to your project in the following directory:
assets/fonts/[fontname].ext

Now in your layout file (main.xml in this case) you would create a TextView as you normally would...
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
>
    <TextView
        android:id="@+id/textViewDefault"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Default Font Text..."
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:textSize="30sp" />
    <TextView
        android:id="@+id/textViewCustom"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Custom Font Text..."
        android:textSize="30sp"
        android:layout_below="@+id/textViewDefault"
        android:layout_alignParentLeft="true"
        android:layout_marginTop="100dp" />
</RelativeLayout>


Now in your activity you create a TypeFace object.
Typeface tf = Typeface.createFromAsset( getAssets(), "fonts/cheyenne_1.ttf" );


Then get the TextView
TextView tv = (TextView)findViewById( R.id.textViewCustom );


Then bind the TypeFace to the TextView
tv.setTypeface( tf );


Now take a look and you will see something like this...



Added source on Google Code: https://code.google.com/p/tutorial-android-custom-font/

Download the apk here:

No comments:

Post a Comment