Sunday, December 12, 2010

Android #5: Working with Custom Fonts

All Android devices comes with a standard collection of fonts namely Droid Sans, Droid Sans Mono, and Droid Serif as they are designed to be optimal for mobile displays. But there might be a need for using custom fonts for some special purposes say for example, Indic Tamil fonts which Android doesn’t support currently. So as a workaround in getting such fonts for a special need, we can go with using custom fonts features that Android supports.

Following example illustrates on using custom fonts in Android application



layout/main.xml:

<?xml version="1.0" encoding="utf-8"?>
<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:layout_width="fill_parent"
android:layout_height="wrap_content" android:textSize="27px"
android:text="@string/msg" />
<!-- Line -->
<View android:layout_width="fill_parent" android:layout_height="2dp"
android:background="#99CCFF" />
<TextView android:id="@+id/tamilTxtId" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:textSize="27px"
android:textColor="#CDE472" />
<TextView android:id="@+id/txtId" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="@string/engFont"
android:textSize="27px" android:textColor="#CDE472" />
</LinearLayout>

CustomFontActivity.java:

package in.satworks.android.samples.activity;import android.app.Activity;
import android.graphics.Typeface;
import android.os.Bundle;
import android.widget.TextView;

public class CustomFontActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Use ENGLISH font
Typeface face=Typeface.createFromAsset(getAssets(), "fonts/VLADIMIR.ttf">
TextView txtView=(TextView)findViewById(R.id.txtId);
txtView.setTypeface(face);
// Use TAMIL font
Typeface tamilFace=Typeface.createFromAsset(getAssets(), "fonts/Eltpan-n.ttf");
TextView tamilTxtView=(TextView)findViewById(R.id.tamilTxtId);
tamilTxtView.setText("1: \u0053\u00D6\u005D\u00EB \u0045\u005D\u00EB \u0053\u0081\u0054\u005D\u00EB");
tamilTxtView.setTypeface(tamilFace);
}
}
Custom Fonts:
Custom font files need to be dropped under assets folder of your android project
  • assets/fonts/VLADIMIR.TTF
  • assets/fonts/Eltpan-n.ttf

1 comment:

  1. Dude this is awesome.... There is another way to do it but for my needs this is great. U r awesome dude.

    ReplyDelete