Creating Custom Text View to apply Custom Font
Creating custom text view in android is a breeze.You just have to follow few very simple steps.
Step 1:Create a attributes file (say attrs.xml) in res/values folder.This is how android lets you define attributes for your custom view
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="CustomFont">
<attr name="font_name" format="string"/>
</declare-styleable>
</resources>
Step 2: Create a class by extending the TextView.Fetch the custom font name & set the typeface.
public class CustomFont extends TextView {
public CustomFont(Context context) {
super(context);
}
public CustomFont(Context context, AttributeSet attrs) {
super(context, attrs);
init(context,attrs);
}
public CustomFont(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context,attrs);
}
private void init(Context context,AttributeSet attrs){
TypedArray attributes=context.obtainStyledAttributes(attrs,R.styleable.CustomFont);
if(attributes!=null){
String fontName=attributes.getString(R.styleable.CustomFont_font_name);
if(fontName!=null){
Typeface tf=Typeface.createFromAsset(context.getAssets(),fontName);
setTypeface(tf);
}
}
attributes.recycle();
}
}
Step 3:Add your custom text view in the layout.Specify the font name (.ttf file).In my case ,font is placed in assets folder.Hence,the path would be:"YOUR_FONTNAME.ttf"
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
xmlns:custom="http://schemas.android.com/apk/res-auto"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
android:background="@android:color/holo_blue_dark"
tools:context=".MainActivity">
<escape.rajeevkr.studio.com.lollypoptest.CustomFont
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Custom Font"
android:layout_centerInParent="true"
android:textSize="25sp"
android:textColor="@android:color/white"
custom:font_name="customfont.ttf"
/>
</RelativeLayout>
And That's it.You are done creating your Custom Text View.It would look something like this.
Happy Coding,
-Rajeev