Using
a .ttf or .otf font in Android is fairly straightforward. Firstly
create ‘assets/fonts/’ and put the files in there. Now using
Typeface.createFromAsset we can create the typeface.
Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/HandmadeTypewriter.ttf");
To set TextView to use
this typeface we use the setTypeface function.
TextView tv = (TextView) findViewById(R.id.texty); tv.setTypeface(tf); The Typeface class specifies the typeface and intrinsic style of a font. This is used in the paint, along with optionally Paint
settings like textSize, textSkewX, textScaleX to specify how text appears when drawn (and measured). Here is our java class: public class CustomFontsActivity extends Activity { /** Called when the activity is first created. */ TextView customStyle1,customStyle2; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Typeface tf1 = Typeface.createFromAsset(getAssets(), "fonts/HandmadeTypewriter.ttf"); Typeface tf2 = Typeface.createFromAsset(getAssets(), "fonts/MgOpenCosmeticaBold.ttf"); customStyle1 = (TextView)findViewById(R.id.text); customStyle2 = (TextView)findViewById(R.id.text1); customStyle1.setTypeface(tf1); customStyle2.setTypeface(tf2); } } Here is our main.xml: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:layout_marginTop="50dp" android:layout_width="fill_parent" android:id="@+id/text" android:textSize="25dp" android:layout_height="wrap_content" android:text="This HandmadeTypewriter style" /> <TextView android:layout_marginTop="50dp" android:layout_width="fill_parent" android:id="@+id/text1" android:textSize="20dp" android:layout_height="wrap_content" android:text="This is MgOpenCosmeticaBold style" /> </LinearLayout>
Here is the Screen Shot:
No comments:
Post a Comment