Pages

Saturday 19 October 2013

Custom Fonts


Android allows us to use the Custom Fonts to use in android development.

Download custom font(.otf ) from the internet
Eg:- http://www.fontsquirrel.com/fonts/kaushan-script (KaushanScript-Regular.otf)

Create  an Android Application Project
Create an assets folder in the project and add downloaded KaushanScript-Regular.otf .




MainActivity.java

package com.example.customfonts;

import android.os.Bundle;
import android.app.Activity;
import android.graphics.Typeface;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {

TextView tv;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        tv = (TextView) findViewById(R.id.textView1);
        
        Typeface tp1 = Typeface.createFromAsset(getAssets(), "KaushanScript-Regular.otf");
        tv.setTypeface(tp1);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}

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.

Typeface.createFromAsset(AssetManager mgr, String path)  creates a new typeface from the specified font data.
Parameter
    mgr --> The application's Asset manager
    path --> The file name of the font data in the assets directory

http://developer.android.com/reference/android/graphics/Typeface.html

setTypeface() sets the typeface to the corresponding textview.

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/margin"
        android:text="TextView"
        android:textSize="@dimen/textsize" />

</RelativeLayout>





No comments:

Post a Comment